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?
解题思路:使用栈非递归完成二叉树的中序遍历,记录每次出栈的节点pre,当前栈顶的节点node。
若pre为node的孩子或者为null,则node出栈;若pre不为空且不是node的孩子,node有孩子,则node孩子入栈。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<Integer>();
Stack<TreeNode> stack=new Stack<TreeNode>();
TreeNode node=root;
TreeNode pre=null;
if(root==null){
return result;
}
stack.push(node);
while(!stack.isEmpty()){
node=stack.peek();
if((pre==null||(pre!=node.left&&pre!=node.right))&&(node.right!=null||node.left!=null)){
if(node.right!=null){
stack.push(node.right);
}
if(node.left!=null){
stack.push(node.left);
}
}else{
result.add(node.val);
stack.pop();
pre=node;
}
}
return result;
}
}