← Trees

Binary Tree Paths

Easy
Python
def binary_tree_paths(root):
    if not root: return []
    if not root.left and not root.right: return [str(root.val)]
    paths=[]
    for child in [root.left,root.right]:
        if child:
            for path in binary_tree_paths(child):
                paths.append(str(root.val)+'->'+path)
    return paths
Java
public List<String> binaryTreePaths(TreeNode root){
    List<String> paths=new ArrayList<>();
    if(root==null) return paths;
    if(root.left==null&&root.right==null){paths.add(String.valueOf(root.val));return paths;}
    for(String path:binaryTreePaths(root.left)) paths.add(root.val+"->"+path);
    for(String path:binaryTreePaths(root.right)) paths.add(root.val+"->"+path);
    return paths;
}

Key Insight

Python iterates [left,right] cleanly. str() vs String.valueOf().

Python → Java Differences

  • str() vs String.valueOf()
  • Iterate children list Python
  • Path building identical
Python
def binary_tree_paths(root):
    if not root: return []
    if not root.left and not root.right: return [str(root.val)]
    paths=[]
    for child in [root.left,root.right]:
        if child:
            for path in binary_tree_paths(child):
                paths.append(str(root.val)+'->'+path)
    return paths
Java
public List<String> binaryTreePaths(TreeNode root){
    List<String> paths=new ArrayList<>();
    if(root==null) return paths;
    if(root.left==null&&root.right==null){paths.add(String.valueOf(root.val));return paths;}
    for(String path:binaryTreePaths(root.left)) paths.add(root.val+"->"+path);
    for(String path:binaryTreePaths(root.right)) paths.add(root.val+"->"+path);
    return paths;
}

Algorithm Steps

1. Leaf: return value
2. Recurse and prepend