您的位置:首页 > 其它

leetcode - 112. Path Sum

2018-01-30 13:12 411 查看
Problem:

 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,求解在树中是否有一条从根结点到叶节点的路径,满足所有val相加等于这个sum。

Solve:

 调用递归进行遍历,思想是先判断当前结点是否满足sum-val=0?(题目给出的树都是正整数的情况)。不等的话再看左右结点,传入sum-val。

 (时间复杂度O(n)AC-1ms
public boolean hasPathSum(TreeNode root, int sum) {
if(root==null){
return false;
}
if (sum-root.val==0&&root.right==null&&root.left==null){//叶节点的情况
return true;
}
if(hasPathSum(root.right,sum-root.val)){
return true;
}
if (hasPathSum(root.left, sum - root.val)) {
return true;
}
return false;
}

后记:思想很明确,注意的地方在于路径需要是根结点到叶结点。中间结点即使找到了答案(sum-val=0)的情况也不能返回true。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: