Leetcode OJ: Path Sum

Path Sum

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.

For example:
Given the below binary tree and sum = 22,

              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.

判断是否存在“从根到叶”的路径使得其和为给定的值。面对这种问题直接上递归吧。递归关系就是:

1. 当到叶子节点时,计算叶子节点值是否与当前要求的和相等

2. hasPathSum(root, sum) = hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val)

记住到叶子节点是判断相等关系的,因为每次递归时都会用要求的和减去当前节点时,到叶子节点时则只需要判断相等即可。

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool hasPathSum(TreeNode *root, int sum) {
13         if (root == NULL)
14             return false;
15         if (sum == root->val && root->left == NULL && root->right == NULL)
16             return true;
17         return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
18     }
19 };

 

posted @ 2014-03-21 19:51  flowerkzj  阅读(113)  评论(0编辑  收藏  举报