Thinking process I - traversal
visit every node
public class Solution {
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
if (root == null) return result;
dfsHelper(result, root, String.valueOf(root.val));
return result;
}
private void dfsHelper(List<String> result, TreeNode root, String path) {
if (root.left == null && root.right == null) {//leaf
result.add(path);
return;
}
if (root.left != null) {
dfsHelper(result, root.left, path + "->" + root.left.val);
}
if (root.right != null) {
dfsHelper(result, root.right, path + "->" + root.right.val);
}
}
}
Thinking process II - Divide and Conquer
add current node with what is returned from left subtree
then add current node with what is returned from right subtree
Mistakes
don't forget the leaf node
public class Solution {
/**
* @param root the root of the binary tree
* @return all root-to-leaf paths
*/
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
if (root == null) return result;
List<String> leftPaths = binaryTreePaths(root.left);
List<String> rightPaths = binaryTreePaths(root.right);
for (String path : leftPaths) {
result.add(root.val + "->" + path);
}
for (String path : rightPaths) {
result.add(root.val + "->" + path);
}
if (result.size() == 0) {
result.add(String.valueOf(root.val));
}
return result;
}
}