[LeetCode] Path Sum

2014-11-24 01:24:16 · 作者: · 浏览: 2
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.
问题描述:给定一个二叉树和一个和值,判断这个二叉树是否有一条从根节点到叶节点的路径,该路径上的节点的值的和等于给定的和值。
看到二叉树的题目,就想到了递归,这道题也可以先看看递归方法。
如果到了叶节点,它的值和给定的值相等,那么就存在一条路径。然后遍历左右子树。
class Solution {  
public:  
    bool hasPathSum(TreeNode *root, int sum) {  
        // IMPORTANT: Please reset any member data you declared, as  
        // the same Solution instance will be reused for each test case.  
        if(root == NULL)  
            return false;  
        else if(root->left == NULL && root->right == NULL && sum == root->val)  
            return true;  
              
        return hasPathSum(root->left, sum-(root->val)) || hasPathSum(root->right, sum-(root->val));  
    }  
};