Binary Tree Paths
Question (LC.257)
Example
I: [1,2,3,null,4,5]
O: ["1->2->4", "1->3->5"]
I: []
O: []Bottom-up D&C
// the report type is fine we can just use it
// recursive definition report all paths from yourself to your leaves
public List<String> binaryTreePaths(TreeNode root) {
List<String> currentPaths = new ArrayList<>();
// base
if (root == null) {
return currentPaths;
}
if (root.left == null && root.right == null) {
currentPaths.add(Integer.toString(root.val));
}
// divide
List<String> leftPaths = binaryTreePaths(root.left);
List<String> rightPaths = binaryTreePaths(root.right);
// merge
for (String path : leftPaths) {
currentPaths.add(root.val + "->" + path);
}
for (String path : rightPaths) {
currentPaths.add(root.val + "->" + path);
}
return currentPaths;
}Top-down Traverse
Last updated