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.
Explanation:
给出一棵树和一个数值,找出从根结点到叶子结点是否存在一条路径,让路径上数值总和等于给定的数。
My Thinking:
通过递归,没过一个结点就计算之前结点到现在为止的总和nowval,直到叶子结点再进行判断。
My Solution:
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
return traversal(root,sum,0);
}
public boolean traversal(TreeNode root,int sum,int nowval){
if(root==null)
return false;
nowval+=root.val;
if(root.left==null && root.right==null)
return sum==nowval;
return traversal(root.left,sum,nowval)||traversal(root.right,sum,nowval);//有一条分支为true即可
}
}
Optimum Thinking:
同样使用递归,从根开始用sum-当前结点的值,直到叶子结点判断剩余的值是否等于0。
Optimum Solution:
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
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);
}
}