Binary Tree Postorder Traversal Java

来源:互联网 发布:除了程序员还有能 编辑:程序博客网 时间:2024/06/06 01:36

Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1    \     2    /   3

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

Check for coding below in detail:

  /*    Key to Solve: Stack1, Stack2(reverse order of stack1)    PostOrder: Left -> right -> root     */public class Solution {    public List<Integer> postorderTraversal(TreeNode root) {       List<Integer> out =new ArrayList<Integer>();        if(root==null) return out;        Stack<TreeNode> stack1=new Stack<TreeNode>();        Stack<TreeNode> stack2=new Stack<TreeNode>();        stack1.push(root);        while(!stack1.isEmpty()){            root=stack1.pop();            //push into stack2 for reversing            stack2.push(root);            //base of LIFO            if(root.left!=null) stack1.push(root.left);            if(root.right!=null) stack1.push(root.right);        }        while(!stack2.isEmpty()){            out.add(stack2.pop().val);        }        return out;    }}


0 0
原创粉丝点击