Wednesday, September 10, 2014

Path Sum -- Leetcode

Question:
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.

Answer:
class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum) {
        if(!root)return false;
        else if(!root->left&&!root->right&&root->val==sum) return true;
        else{
            if(hasPathSum(root->left,sum-root->val)||hasPathSum(root->right,sum-root->val)){
                return true;
            }
            else
               return false;
        }
    }
};

No comments:

Post a Comment