My ugly code,Runtime: 3 ms,Can you improve it..


  • 0
    L

    public void traveltree(List<String> Lists,List<Integer> path,TreeNode root){
    StringBuffer str=new StringBuffer();
    if(root==null){
    path.remove(path.size()-1);
    return;
    }
    path.add(root.val);
    if(root.left==null&&root.right==null){
    for(int i=0;i<path.size();i++){
    str.append(path.get(i));
    if(i!=path.size()-1){
    str.append("->");
    }
    }
    Lists.add(str.toString());
    }
    if(root.left!=null)
    traveltree(Lists,path,root.left);
    if(root.right!=null)
    traveltree(Lists,path,root.right);

        if(path.size()!=0)
            path.remove(path.size()-1);
    }
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> Lists=new LinkedList<String>();
        List<Integer> path=new ArrayList<Integer>();
        if(root==null){
            return Lists;
        }
        traveltree(Lists,path,root);
        return Lists;
    
    }

Log in to reply
 

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