path_sum_III

You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1

Return 3. The paths that sum to 8 are:

1.  5 -> 3
2.  5 -> 2 -> 1
3. -3 -> 11

题目就是求和为8的向下的路径数
1,2,3,4,5是连续的五段路程不能跳过。如果想到站点5到达各地有几条路程,5->4->3->2->15->4->3->25->4->3
5->4,有四条路径。找和为8的路径只是多加了个条件。首先我们以root为节点,向下查找,再以root的左右儿子为节点查找,然后左右儿子又以自己的左右儿子为节点向下查找。所以用递归来完成。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
int res = 0;
if(root == NULL)
return res;
return dfs(root,sum)+pathSum(root->left,sum)+pathSum(root->right,sum);
}
int dfs(TreeNode* root,int sum){
int res = 0;
if(root == NULL)
return res;
if(root->val == sum)
res++;
res+= dfs(root->left,sum-root->val);
res+= dfs(root->right,sum-root->val);
return res;


}
};

这里的深度搜索dfs和下面求平衡二叉树时的depth是类似的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
bool isBalanced(TreeNode* root) {
if(root == NULL)
return true;
if(root->left == NULL&&root->right == NULL)
return true;
if(abs(depth(root->left)-depth(root->right))>1)
return false;
return isBalanced(root->left)&&isBalanced(root->right);
}
int depth(TreeNode* root){
if(root == NULL)
return 0;
return max(1+depth(root->left),1+depth(root->right));
}
};

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×