Given a binary tree, return all root-to-leaf paths.
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
getTreePaths(root, "", res);
return res;
}
public void getTreePaths(TreeNode node, String curPath, List<String> res) {
if (node == null) {
return;
}
if (node.left == null && node.right == null) {
res.add(curPath + node.val);
return;
}
getTreePaths(node.left, curPath + node.val + "->", res);
getTreePaths(node.right, curPath + node.val + "->", res);
}
}
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if (root == null) {
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
Queue<String> path = new LinkedList<>();
queue.add(root);
path.add("");
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode curNode = queue.remove();
String curPath = path.remove();
if (curNode.left == null && curNode.right == null) {
res.add(curPath + curNode.val);
}
if (curNode.left != null) {
queue.add(curNode.left);
path.add(curPath + curNode.val + "->");
}
if (curNode.right != null) {
queue.add(curNode.right);
path.add(curPath + curNode.val + "->");
}
}
}
return res;
}
}
3. Time & Space Complexity