1. 程式人生 > 實用技巧 >leetcode 38:path-sum

leetcode 38:path-sum

題目描述

給定一個二叉樹和一個值sum,判斷是否有從根節點到葉子節點的節點值之和等於sum的路徑,
例如:
給出如下的二叉樹,sum=22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
返回true,因為存在一條路徑5->4->11->2的節點值之和為22


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 andsum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1

return true, as there exist a root-to-leaf path5->4->11->2which sum is 22.

示例1

輸入

複製
{1,2},0

輸出

複製
false
示例2

輸入

複製
{1,2},3

輸出

複製
true


/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/

class Solution {
public:
/**
*
* @param root TreeNode類
* @param sum int整型
* @return bool布林型
*/
bool hasPathSum(TreeNode* root, int sum) {
// write code here
if (root==NULL){
return false;
}
if(root->left ==NULL && root->right==NULL && sum-root->val==0)
return true;
return hasPathSum(root->left, sum-root->val)||hasPathSum(root->right, sum-root->val);
}
};