Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1
/ \
2 3
\
5
All root-to-leaf paths are:
["1-
>
2-
>
5", "1-
>
3"]
Credits:
Special thanks to@jianchao.li.fighterfor adding this problem and creating all test cases.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private class Node{
TreeNode nd;
String path;
public Node(TreeNode nd, String path){
this.nd = nd;
this.path = path;
}
}
public List<String> binaryTreePaths(TreeNode root) {
List<String> ans = new ArrayList<>();
if (root == null) return ans;
Queue<Node> q = new LinkedList<>();
q.offer(new Node(root, root.val + ""));
while (!q.isEmpty()){
Node cur = q.poll();
if (cur.nd.left == null && cur.nd.right == null){
ans.add(cur.path);
}
if (cur.nd.left != null){
q.offer(new Node(cur.nd.left, cur.path + "->" + cur.nd.left.val));
}
if (cur.nd.right != null){
q.offer(new Node(cur.nd.right, cur.path + "->" + cur.nd.right.val));
}
}
return ans;
}
}