257. Binary Tree Paths

https://leetcode.com/problems/binary-tree-paths/

time: O(n)

space: O(n)

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if (root == null) return res;
        helper(root, res, "");
        return res;
    }
    private void helper(TreeNode root, List<String> res, String path) {
        if (root == null) return; //terminator 1
        path += root.val;
        if (root.left == null && root.right == null) { //terminator 2
            res.add(path);
        }
        helper(root.left, res, path + "->");   //drill down
        helper(root.right, res, path + "->");  //drill down
    }
}

using StringBuilder is faster

ๅฆ‚ๆžœไธๅฆๅค–่ค‡่ฃฝไธ€ๅ€‹ sbไพ†็”จ็š„่ฉฑ, ๆœƒ่ฎŠๆˆ้€™ๆจฃ, sb ๆœƒๆŒ็บŒ่ขซๅŠ ไธŠ่ณ‡ๆ–™

Output Data
["1->2->5","1->2->5->3"]
Expected
["1->2->5","1->3"]
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        helper(root, res, new StringBuilder());
        return res;
    }
    private void helper(TreeNode root, List<String> res, StringBuilder sb) {
        if (root == null) { // terminator 1
            return;
        }
        sb.append(root.val);
        if (root.left == null && root.right == null) { // terminator 2
            res.add(sb.toString());
        }
        sb.append("->");
        String sbTemp = sb.toString(); // if use sb, it should create another sb object to run
        
        helper(root.left, res, sb);  // drill down
        helper(root.right, res, new StringBuilder(sbTemp)); // drill down
    }
}

Last updated