Skip to content

Latest commit

 

History

History
49 lines (38 loc) · 892 Bytes

257. Binary Tree Paths.md

File metadata and controls

49 lines (38 loc) · 892 Bytes

257. Binary Tree Paths

Problem

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

1 /
2 3
5 All root-to-leaf paths are:

["1->2->5", "1->3"]

tag:

  • Tree

Solution

java

    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<String>();
        helper(res, new StringBuilder(), root);
        return res;
    }
    
    void helper(List<String> res, StringBuilder str, TreeNode root) {
        if(root==null) return;
        int len = str.length();
        str.append(root.val);
        if(root.left==null && root.right==null) {
            res.add(str.toString());
        } else {
            str.append("->");
            helper(res, str, root.left);
            helper(res, str, root.right);
        }
        str.setLength(len);
    }

go