3ms Java Solution, any suggestions for imporvement?


  • 0
    L
    public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<String>();
        if(root == null) return res;
        if(root.left==null && root.right==null){
            res.add(String.valueOf(root.val));
            return res;
        }
        if(root.left!=null){
            dfs(root.left, String.valueOf(root.val), res);
        }
        if(root.right!=null){
            dfs(root.right, String.valueOf(root.val), res);
        }
        return res;
    }
    private void dfs(TreeNode root, String path, List<String> res){
        StringBuilder sb = new StringBuilder(path);
        sb.append("->").append(root.val);
        if(root.left == null && root.right == null){
            res.add(sb.toString());
        }
        if(root.left!=null){
            dfs(root.left, sb.toString(), res);
        }
        if(root.right!=null){
            dfs(root.right, sb.toString(), res);
        }
    }
    

    }


  • 0
    W

    sb.toString() may be called twice in a dfs(). This will be faster.

    private void dfs(TreeNode root, String path, List<String> res){
        String base = path + "->" + root.val;
        if(root.left == null && root.right == null){
            res.add(base);
        }
        if(root.left!=null){
            dfs(root.left, base, res);
        }
        if(root.right!=null){
            dfs(root.right, base, res);
        }
    }

  • 0
    L

    looks like the time is not improved..


Log in to reply
 

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