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

2018/05/25 re-do the question

divide and conquer but you forget that when you meet the leaf nodes you have to

  • [x] if (ans.size() == 0) { ans.add(""+root.val); }

add Edward solution 2 also O(n) time and space

Attention: when you encounter the leaf node !!! what should you do? ?!!? !

Example

Given the following binary tree:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

[
  "1->2->5",
  "1->3"
]
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: the root of the binary tree
     * @return: all root-to-leaf paths
     */
    public List<String> binaryTreePaths(TreeNode root) {
        // write your code here
        List<String> ans = new ArrayList<>();
        if (root == null) {
            return ans;
        }
        List<String>  left = binaryTreePaths(root.left);
        List<String>  right = binaryTreePaths(root.right);
        for (String path : left) {
            ans.add(root.val + "->" + path);
        }
         for (String path : right) {
            ans.add(root.val + "->" + path);
        }
        if (ans.size() == 0) {
            ans.add(""+root.val);
        }
        return ans;
    }
}

Edward

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> ans = new ArrayList<>();
        if (root == null) {
            return ans;
        }
        helper(root, ans, "");
        return ans;
    }
    public void helper(TreeNode root, List<String> ans, String path) {
        // if it is the leaf node then add the path
        if (root.left  == null && root.right == null) {
            ans.add(path + root.val);
            return;
        }
        if (root.left != null) {
            helper(root.left, ans, path + root.val + "->");
        }
        if (root.right != null) {
            helper(root.right, ans, path + root.val + "->");
        }
    }
}

results matching ""

    No results matching ""