Simple Solution in Java, both recursion and iteration


  • 2
    W

    recursion(308ms):

    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result=new ArrayList<String>();
        if(root==null)return result;
        helper(result,root,"");
        return result;
    }
    private void helper(List<String> result,TreeNode root,String str){
        str+=root.val;
        if(root.left==null&&root.right==null){
            result.add(str);
            return;
        }
        if(root.left!=null){
            helper(result,root.left,str+"->");
        }
        if(root.right!=null){
            helper(result,root.right,str+"->");
        }
    }
    

    iteration(304ms):

    public List<String> binaryTreePaths(TreeNode root) {
        Queue<TreeNode> nodes=new LinkedList<TreeNode>();
        Queue<String> strs=new LinkedList<String>();
        List<String> result=new ArrayList<String>();
        if(root!=null){
            nodes.offer(root);
            strs.offer(Integer.toString(root.val));
        }
        while(!nodes.isEmpty()){
            TreeNode node=nodes.poll();
            if(node.left==null&&node.right==null){
                result.add(strs.poll());
            }else{
                String newStr=strs.poll();
                if(node.left!=null){
                    nodes.offer(node.left);
                    strs.offer(newStr+"->"+node.left.val);
                }
                if(node.right!=null){
                    nodes.offer(node.right);
                    strs.offer(newStr+"->"+node.right.val);
                }
            }
        }
        return result;
    }

Log in to reply
 

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