Path Sum
Solution to Path Sum problem. I came up with this solution, but was blown away when I saw the solution by Lazy Coder.
class Solution {
boolean result = false;
public boolean hasPathSum(TreeNode root, int sum) {
int curSum = 0;
preOrderTraverse(root, sum, curSum);
return result;
}
private void preOrderTraverse(TreeNode node, int sum, int curSum) {
if(node == null)
return;
curSum = curSum + node.val;
if (curSum == sum && isLeafNode(node)) {
result = true;
return;
}
preOrderTraverse(node.left, sum, curSum);
preOrderTraverse(node.right, sum, curSum);
}
private boolean isLeafNode(TreeNode node) {
return node.left == null && node.right == null;
}
}
More elegant solution :
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) {
return false;
}
if (sum == root.val && root.left == null && root.right == null) {
return true;
}
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
}