Question
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.
Solution 1 -- Recursion
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null)
return false;
int total = 0;
return dfs(root, sum, total);
} private boolean dfs(TreeNode root, int target, int prevSum) {
if (root == null)
return false;
int currentSum = prevSum + root.val;
if (root.left == null && root.right == null) {
return currentSum == target;
} else {
return (dfs(root.left, target, currentSum) || dfs(root.right, target, currentSum));
} }
}
Solution 2 -- BFS
We can use two stacks here. One to record tree nodes. And the other to record current path sum from root to this node. Since we traverse the tree level by level. It's BFS.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null)
return false;
Stack<TreeNode> stack1 = new Stack<TreeNode>();
Stack<Integer> stack2 = new Stack<Integer>();
stack1.push(root);
stack2.push(0);
while (!stack1.empty()) {
TreeNode currentNode = stack1.pop();
int currentSum = stack2.pop() + currentNode.val;
if (currentNode.left == null && currentNode.right == null && currentSum == sum)
return true;
if (currentNode.left != null) {
stack1.push(currentNode.left);
stack2.push(currentSum);
}
if (currentNode.right != null) {
stack1.push(currentNode.right);
stack2.push(currentSum);
}
}
return false;
}
}