Task

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

Example

Given the below binary tree and sum = 22,

1
2
3
4
5
6
7
      5
     / \
    4   8
   /   / \
  11  13  4
 /  \      \
7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

Solution

  • 递归求解,递归终止条件是叶子节点。
  • 每次往下走都将所求的sum减去当前节点,得到下面节点应该具有的和new_sum
  • 递归终止条件:
    • 走到叶子节点(即无左右子树)时只需判断当前节点的值是否等于最新的new_sum
    • 走到叶子节点以下的空指针时直接返回false
  • 时间复杂度:只需遍历每个节点一次,在每个节点处更新new_sum,故O(n)
  • 空间复杂度:递归取决于树的高度O(h)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Runtime: 20 ms, faster than 48.13% of C++ online submissions for Path Sum.
// Memory Usage: 21.5 MB, less than 6.15% of C++ online submissions for Path Sum.
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        if(!root) return false;
        if(!root->left && !root->right) return root->val==sum;
        int new_sum=sum-root->val;
        return hasPathSum(root->left,new_sum)
            || hasPathSum(root->right,new_sum);
    }
};