Binary Tree Paths

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

Example:

Given the following binary tree:

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

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

Code:

public class Solution {
    /**
     * @param root the root of the binary tree
     * @return all root-to-leaf paths
     */
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        dfs(root, new ArrayList<Integer>(), res);
        return res;
    }

    private void dfs(TreeNode root, ArrayList<Integer> path, List<String> res) {
        path.add(root.val);
        if (root.left == null && root.right == null) {
            res.add(formatedPath(path));
        } else {
            if (root.left != null) {
                dfs(root.left, path, res);
            }
            if (root.right != null) {
                dfs(root.right, path, res);
            }
        }
        path.remove(path.size() - 1);
    }

    private String formatedPath(ArrayList<Integer> path) {
        StringBuilder sb = new StringBuilder();
        for (int x : path) {
            sb.append(x);
            sb.append("->");
        }
        if (path.size() > 0) {
            sb.setLength(sb.length() - 2);
        }
        return sb.toString();
    }
}

results matching ""

    No results matching ""