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<String>();
        if (root == null) {
            return ans;
        }
        String cur = "";
        btpDFS(root, ans, cur);
        return ans;
    }

    public void btpDFS(TreeNode root, List<String> ans, String cur) {
        if (root == null) {
            return;
        }

        cur = cur + root.val + "->";

        if (root.left == null && root.right == null) {
            cur = cur.substring(0, cur.lastIndexOf("->"));
            ans.add(new String(cur));
            return;
        }

        if (root.left != null) {
            btpDFS(root.left, ans, cur);
        }
        if (root.right != null) {
            btpDFS(root.right, ans, cur);
        }

        cur = cur.substring(0, cur.lastIndexOf("->"));
    }
}

second batch

public List<String> binaryTreePaths(TreeNode root) {
        // Write your code here
        List<String> ans = new ArrayList<String>();
        if (root == null) {
            return ans;
        }

        String cur = "";
        binaryTreePathsHelper(ans, cur, root);
        return ans;
    }


    public void binaryTreePathsHelper(List<String> ans, String cur, TreeNode root){
        if (root == null) {
            return;
        }

        cur = cur + root.val + "->";

        binaryTreePathsHelper(ans, cur, root.left);
        binaryTreePathsHelper(ans, cur, root.right);

        if (root.left == null && root.right == null) {
            ans.add(new String(cur.substring(0, cur.lastIndexOf("->"))));
        }

        cur = cur.substring(0, cur.lastIndexOf("->"));

    }

results matching ""

    No results matching ""