[Leetcode]-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.
Hide Tags :Tree, Depth-first Search
題目:找出二叉樹中是否有從根節點到樹葉路徑的值之和等於給定的數據sum
思路:凡是設計到二叉樹的查找,搜索…採用遞歸是一種較好的方法。
1、給出遞歸終止條件,也就是
A:當節點為NULL時返回false
B:當節點為樹葉(無兒子節點)時,檢查此樹葉的val是否與sum相等,相等則返回true。否則返回false
2、當不是終止條件B時。繼續向下遞歸。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool hasPathSum(struct TreeNode* root, int sum) {
if(root == NULL) return false;
if(root->left == NULL && root->right == NULL) return sum == root->val;
return (hasPathSum(root->left,sum - root->val) || hasPathSum(root->right,sum - root->val));
}
[Leetcode]-Path Sum