Root to leaf path sum equal to a given number
Given a binary tree and a number, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals the given number. Return false if no such path can be found.
I have written 3 solutions: one recursive, one using 2 stacks (DFS), and last one using 2 queues (BFS). I am looking for improvements and suggestions.
// Recursive version
public static boolean hasPathSum1 (Node root, int sum) {
if (root == null) {
return false;
}
if(root.left == null && root.right == null && root.data == sum) {
return true;
}
return hasPathSum1(root.left, sum - root.data) ||
hasPathSum1(root.right, sum - root.data);
}
//===========================================================================
// Iterative version (DFS) - Using 2 Stacks
public static boolean hasPathSum2 (Node root, int sum) {
if (root == null) {
return false;
}
Stack<Node> nodes = new Stack<Node>();
Stack<Integer> values = new Stack<Integer>();
nodes.push(root);
values.push(root.data);
while (!nodes.isEmpty()) {
Node current = nodes.pop();
int sumValue = values.pop();
if (current.left == null && current.right == null && sumValue == sum) {
return true;
}
if (current.left != null) {
nodes.push(current.left);
values.push(current.left.data + sumValue);
}
if (current.right != null) {
nodes.push(current.right);
values.push(current.right.data + sumValue);
}
}
return false;
}
//========================================================================
// Iterative version (BFS) - Using 2 queues
public static boolean hasPathSum3 (Node root, int sum) {
if(root == null) {
return false;
}
Queue<Node> nodes = new LinkedList<Node>();
Queue<Integer> values = new LinkedList<Integer>();
nodes.add(root);
values.add(root.data);
while(!nodes.isEmpty()){
Node current = nodes.remove();
int sumValue = values.remove();
if(current.left == null && current.right == null && sumValue == sum){
return true;
}
if(current.left != null){
nodes.add(current.left);
values.add(current.left.data + sumValue);
}
if(current.right != null){
nodes.add(current.right);
values.add(current.right.data + sumValue);
}
}
return false;
}