?LeetCode刷題實戰(zhàn)437:路徑總和 III
Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
示例

解題
如果問題是這樣:找出以根節(jié)點為開始,任意節(jié)點可作為結(jié)束,且路徑上的節(jié)點和為 sum 的路徑的個數(shù);
是不是前序遍歷一遍二叉樹就可以得到所有這樣的路徑?是的;
如果這個問題解決了,那么原問題可以分解成多個這個問題;
是不是和數(shù)線段是同一個問題,只不過線段變成了二叉樹;
在解決了以根節(jié)點開始的所有路徑后,就要找以根節(jié)點的左孩子和右孩子開始的所有路徑,三個節(jié)點構(gòu)成了一個遞歸結(jié)構(gòu);
/**
?* Definition for a binary tree node.
?* public class TreeNode {
?* int val;
?* TreeNode left;
?* TreeNode right;
?* TreeNode(int x) { val = x; }
?* }
?*/
class?Solution?{
???/**
?????* 求以 root 為根的二叉樹,所有和為 sum 的路徑;
?????* 路徑的開頭不一定是 root,結(jié)尾也不一定是葉子節(jié)點;
?????* @param?root
?????* @param?sum
?????* @return
?????*/
????public?int?pathSum(TreeNode root, int?sum)?{
?
????????if?(root == null) {
????????????return?0;
????????}
?
????????return?paths(root, sum)
????????????????+ pathSum(root.left, sum)
????????????????+ pathSum(root.right, sum);
????}
?
????private?int?paths(TreeNode root, int?sum)?{
?
????????if?(root == null) {
????????????return?0;
????????}
?
????????int?res = 0;
????????if?(root.val == sum) {
????????????res += 1;
????????}
?
????????res += paths(root.left, sum - root.val);
????????res += paths(root.right, sum - root.val);
?
????????return?res;
????}
}
LeetCode刷題實戰(zhàn)421:數(shù)組中兩個數(shù)的最大異或值
LeetCode刷題實戰(zhàn)423:從英文中重建數(shù)字
LeetCode刷題實戰(zhàn)424:替換后的最長重復(fù)字符
LeetCode刷題實戰(zhàn)426:將二叉搜索樹轉(zhuǎn)化為排序的雙向鏈表
LeetCode刷題實戰(zhàn)428:序列化和反序列化 N 叉樹
LeetCode刷題實戰(zhàn)429:N 叉樹的層序遍歷
LeetCode刷題實戰(zhàn)430:扁平化多級雙向鏈表
LeetCode刷題實戰(zhàn)431:將 N 叉樹編碼為二叉樹
LeetCode刷題實戰(zhàn)432:全 O(1) 的數(shù)據(jù)結(jié)構(gòu)
LeetCode刷題實戰(zhàn)434:字符串中的單詞數(shù)
LeetCode刷題實戰(zhàn)435:無重疊區(qū)間
