题目描述
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree{1,#,2,3},![]()
return[3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
- 思路
求后序遍历。
法一:递归(参考中序遍历)
法二:非递归。判断栈顶节点,若无孩子节点或其孩子节点都被访问(将右左孩子依次入栈,保证了根节点始终在子节点之后被访问),则访问该节点,否则把该节点的左右孩子加入栈中(注意顺序)。
//非递归
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(root == null)
return list;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.add(root);
TreeNode pre = null; //前一个访问的节点
while( !stack.isEmpty()){
TreeNode node = stack.peek();
//当是根节点或其子节点都被访问时
if((node.left == null && node.right == null) ||
(pre != null && (pre == node.left || pre == node.right))){
list.add(node.val);
stack.pop();
pre = node;
}else{
if(node.right != null)
stack.add(node.right);
if(node.left != null)
stack.add(node.left);
}
}
return list;
}
}