Binary Tree Paths

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"]

Credits:Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
     public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        binaryTreePaths(root, result, new ArrayList<>());
        return result;
    }

    public void binaryTreePaths(TreeNode root, List<String> result, List<Integer> runner) {
                if (root == null) return;

        if (root.left == null && root.right == null) {
            runner.add(root.val);
            result.add(convert(runner));
            runner.remove(runner.size() - 1);
            return;
        }

        runner.add(root.val);
        if (root.left != null) {
            binaryTreePaths(root.left, result, runner);
        }

        if (root.right != null) {
            binaryTreePaths(root.right, result, runner);
        }
        runner.remove(runner.size() - 1);
    }

    private String convert(List<Integer> input) {
        if (input.isEmpty()) return "";

        StringBuffer sb = new StringBuffer();
        sb.append(input.get(0));
        for (int i = 1; i < input.size(); i++) {
            sb.append("->");
            sb.append(input.get(i));
        }

        return sb.toString();
    }

}

results matching ""

    No results matching ""