# My Java solution in DFS, BFS, recursion

• recursion:

``````public class Solution {
//Recursion
public List<String> binaryTreePaths(TreeNode root) {
//String s=new String();
if (root==null) return sList;
if (root.left==null && root.right==null) {
return sList;
}

for (String s: binaryTreePaths(root.left)) {
}
for (String s: binaryTreePaths(root.right)) {
}
return sList;
}
``````

}

BFS - queue

``````public class Solution {
//BFS - Queue
public List<String> binaryTreePaths(TreeNode root) {
List<String> list=new ArrayList<String>();

if (root==null) return list;
while(!qNode.isEmpty()) {
TreeNode curNode=qNode.remove();
String curStr=qStr.remove();

if (curNode.left!=null) {
}
if (curNode.right!=null) {
}
}
return list;
}
``````

DFS - stack

``````public class Solution {
//DFS - Stack
public List<String> binaryTreePaths(TreeNode root) {
List<String> list=new ArrayList<String>();
Stack<TreeNode> sNode=new Stack<TreeNode>();
Stack<String> sStr=new Stack<String>();

if(root==null) return list;
sNode.push(root);
sStr.push("");
while(!sNode.isEmpty()) {
TreeNode curNode=sNode.pop();
String curStr=sStr.pop();

if(curNode.left!=null) {
sNode.push(curNode.left);
sStr.push(curStr+curNode.val+"->");
}
if(curNode.right!=null) {
sNode.push(curNode.right);
sStr.push(curStr+curNode.val+"->");
}
}
return list;
}``````

• Thank you for sharing. The correspondence of two queues really solves one of my long-lasting question.

• Very good solution, so weird such few people upvote this post. I like the BFS method best.
I actually have a similar idea but I didn't realize to use a second queue for String, instead I use a hashmap to trace each node's parent and then reorganize to get the answer. But it is definitly much more complex than it should be.

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