# My Java solutions using Recursion and Iteration (Queue and Stack)

• recursion:

``````    public class Solution {
//recursion
public boolean hasPathSum(TreeNode root, int sum) {
if (root==null) return false;
//if (sum<root.val) return false;
if (root.left==null && root.right==null) return root.val==sum;
return (hasPathSum(root.left,sum-root.val) || hasPathSum(root.right,sum-root.val));
}
}
``````

Queue:

``````public class Solution {
//Queue
public boolean hasPathSum(TreeNode root, int sum) {

if(root==null) return false;

while (!qNode.isEmpty()) {
TreeNode curNode=qNode.remove();
int curSum=qSum.remove();

if (curNode.left==null && curNode.right==null && curSum==curNode.val) return true;
if (curNode.left!=null) {
}
if (curNode.right!=null) {
}
}
return false;

}
``````

}

Stack:

``````public class Solution {
//stack
public boolean hasPathSum(TreeNode root, int sum) {
Stack<TreeNode> sNode=new Stack<TreeNode>();
Stack<Integer> sSum=new Stack<Integer>();

if (root==null) return false;
sNode.push(root);
sSum.push(sum);
while(!sNode.isEmpty()) {
TreeNode node=sNode.pop();
int curSum=sSum.pop();

if (node.left==null && node.right==null && node.val==curSum) return true;
if (node.left!=null) {
sNode.push(node.left);
sSum.push(curSum-node.val);
}
if(node.right!=null) {
sNode.push(node.right);
sSum.push(curSum-node.val);
}
}
return false;
}
}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.