Leetcode 257. Binary Tree Paths
Given the root
of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children.
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<>();
if (root == null) {
return paths;
}
constructPaths(root, "", paths);
return paths;
}
private void constructPaths(TreeNode node, String path, List<String> paths) {
if (node != null) {
path += Integer.toString(node.val);
if (node.left == null && node.right == null) { // It's a leaf
paths.add(path); // Add the path to the list
} else {
path += "->"; // Prepare for the next node
if (node.left != null) {
constructPaths(node.left, path, paths);
}
if (node.right != null) {
constructPaths(node.right, path, paths);
}
}
}
}
}
By following this approach and code, you should be able to solve the problem of finding all root-to-leaf paths in any binary tree.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?