My java solution for non-recursion version


  • 2
    M
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if(root == null)
            return res;
        String path = new String();
        TreeNode p = root;
        Stack<TreeNode> stack = new Stack<>();
        Stack<String> pathStack = new Stack<>();
        TreeNode pre = null;
        while(p!=null || !stack.isEmpty())
        {
            if(p!=null)
            {
                if(p == root)
                    path = Integer.toString(p.val);
                else
                    path = path+"->"+Integer.toString(p.val);
                
                if(p.left == null && p.right == null)
                    res.add(path);
                pathStack.push(path);
                stack.push(p);
                pre = p;
                p = p.left;
            }
            else
            {
                TreeNode node = stack.pop();
                p = node.right;
                path = pathStack.pop();
            }
        }
        return res;
    }

  • 0
    J

    @moooc Great solution! "TreeNode p" is not necessary here right?


  • 0
    R

    @jiangyifan2bad The "TreeNode pre" is not necessary I think


Log in to reply
 

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