leetcode 112

112. 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.

判断二叉树是否存在一条从根节点到叶子节点的路径是的路径上节点的值之和等于给定的数sum,若存在返回true,否则返回false。

递归解法:每次递归sum都减去当前节点的值,当sum为0且当前节点为叶子节点时返回true;当sum不为0且当前节点为叶子节点时返回false;当sum不为0且当前

                 节点不为叶子节点时,根据当前节点的左右子树的情况,返回左子树的递归调用或右子树的递归调用或者是两者的或(||)。

代码如下:

 

 1 /**
 2  * Definition for a binary tree node.
 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         {
15             return false;
16         }
17         sum -= root->val;
18         if(sum == 0 && root->left == NULL && root->right == NULL)
19         {
20             return true;
21         }
22         else if(root->left == NULL && root->right == NULL)
23         {
24             return false;
25         }
26         else if(root->left == NULL)
27         {
28             return hasPathSum(root->right, sum);
29         }
30         else if(root->right == NULL)
31         {
32             return hasPathSum(root->left, sum);
33         }
34         else
35         {
36             return hasPathSum(root->right, sum) || hasPathSum(root->left, sum); 
37         }
38     }
39 };

 

posted @ 2016-09-28 10:24  花椰菜菜菜菜  阅读(215)  评论(0编辑  收藏  举报