Java simple solution


  • 0
    D
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> paths = new ArrayList<>();
        binaryTreePaths(root, paths, new StringBuilder());
        return paths;
    }
    
    public void binaryTreePaths(TreeNode root, List<String> paths, StringBuilder builder) {
        if(root == null) return;
        if(root.left == null && root.right == null) paths.add(builder.append("->").append(root.val).substring(2));
        builder.append("->").append(root.val);
        if(root.left != null) binaryTreePaths(root.left, paths, new StringBuilder(builder.toString()));
        if(root.right != null) binaryTreePaths(root.right, paths, new StringBuilder(builder.toString()));
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.