Java solution preorder~


  • 0
    X
      public List<String> binaryTreePaths(TreeNode root) {
        List<String> ans = new ArrayList<String>();
        List<Integer> temp = new ArrayList<Integer>();
        
        if(root == null){
            return ans;
        }
        
        temp.add(root.val);
        useme(ans,temp,root);
        return ans;
    }
    
    public void useme(List<String> ans,List<Integer> temp, TreeNode root){
        if(root.left == null && root.right == null){
            StringBuffer sb = new StringBuffer();
            for(int i:temp){
                sb.append(i).append("->");
            }
            sb.delete(sb.length()-2,sb.length());
            ans.add(new String(sb));
            return;
        }
        if(root.left !=null){
            temp.add(root.left.val);
            useme(ans,temp,root.left);
            temp.remove(temp.size()-1);
        }
        
        if(root.right!=null){
            temp.add(root.right.val);
            useme(ans,temp,root.right);
            temp.remove(temp.size()-1);
        }
    }

Log in to reply
 

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