Simple java solution with explanation

  • 1
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        return path(root, res, sb);
    private List<String> path(TreeNode node, List<String> res, StringBuilder pro) {
        if (node == null) {
            return res;
    	StringBuilder pre = new StringBuilder(pro);
        if (node.left == null && node.right == null) {
        pre = new StringBuilder(pro);
        if (node.left != null) {
            path(node.left, res, pre.append(node.val + "->")); 
        if (node.right != null) {
            path(node.right, res, pro.append(node.val + "->"));
        return res;

    idea: if node == null, doesn't add anything. if node has no child, add this node to the result list. if node has child, recursive add left node (if have) and right node (if have).

    should pay attention to the StringBuilder, pre.append(x) will change the original value of pre. So, I keep track of the original StringBuilder. That is the reason why I add the code "StringBuilder pre = new StringBuilder(pro);"

Log in to reply

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