题目
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?
方法
/**
* 要保证根结点在左孩子和右孩子访问之后才能访问,因此对于任一结点P,先将其入栈。
* 如果P不存在左孩子和右孩子,则可以直接访问它;或者P存在左孩子或者右孩子,但是其左孩子和右孩子都已被访问过了,则同样可以直接访问该结点。
* 若非上述两种情况,则将P的右孩子和左孩子依次入栈,
* 这样就保证了每次取栈顶元素的时候,左孩子在右孩子前面被访问,左孩子和右孩子都在根结点前面被访问。
*/
private Stack<TreeNode> stack = new Stack<TreeNode>();
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> al = new ArrayList<Integer>();
if (root != null) {
TreeNode cur = null;
TreeNode pre = null;
stack.push(root);
while (stack.size() != 0) {
cur = stack.peek();
if ((cur.left == null && cur.right == null) || (pre != null && (pre == cur.left || pre == cur.right))) {
al.add(cur.val);
pre = cur;
stack.pop();
} else {
if (cur.right != null) {
stack.push(cur.right);
}
if (cur.left != null) {
stack.push(cur.left);
}
}
}
}
return al;
}