Simple Java solution better than 75%!!


  • 1
    A
    /**
     * 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> res = new ArrayList<String>();
            if (root == null){
                return res;
            }
            return getPaths (root, "", res);
        }
        
        public List<String> getPaths(TreeNode root, String str, List<String> res){
            if (root.left == null && root.right == null){
                if (str.equals("")){
                    str += root.val;
                }
                else {
                    str += "->"+root.val;
                }
                res.add (str);
                return res;
            }
            if (str.equals("")){
                str += root.val;
            }
            else {
                str += "->"+root.val;
            }
            if (root.left != null){
                getPaths (root.left, str, res);
            }
            if (root.right != null){
                getPaths (root.right, str, res);
            }
            return res;
        }
    }

  • 0
    H

    Make res array a field in your solution class and it's gonna be faster and more efficient


Log in to reply
 

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