2ms Java recursive Solution


  • 2
    Y
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> list = new LinkedList<String>();
        if(root==null) return list;
        if(root.left==null&&root.right==null) {
            list.add(""+root.val);
            return list;
        }
        if(root.left!=null) pathString(""+root.val,root.left,list);
        if(root.right!=null) pathString(""+root.val,root.right,list);
        return list;
    }
    public void pathString(String a, TreeNode root, List<String> list){
        String temp = a+"->"+root.val;
        if(root.left==null&&root.right==null) {
            list.add(temp);
            return;
        }
        if(root.left!=null) pathString(temp,root.left,list);
        if(root.right!=null) pathString(temp,root.right,list);
    }

Log in to reply
 

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