您的位置:首页 > 其它

LeetCode解题报告 112. Path Sum [easy]

2017-01-03 11:13 531 查看

题目要求

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。用最基本的DFS即可,判断该节点左右子树是否为空且节点值等于sum,如果是则返回true,而后将sum的值减去跟节点的val值,递归循环判断左孩子节点和右孩子节点,其中一个满足即可。

复杂度分析

时间复杂度为O(N)

代码如下:

class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (root==NULL) {
return false;
}

if (root->val==sum&&root->left==NULL&&root->right==NULL) {
return true;
}
sum=sum-root->val;
return hasPathSum(root->left, sum)||hasPathSum(root->right, sum);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode