- Preorder: print parent directly.
- Inorder: print parent when return from left child.
- Postorder: print parent when return from right child.
可以用堆棧實現非遞歸遍歷
而用堆棧實現又有兩種方式
1.堆棧中存放的是未訪問過的結點,這種方式先讓根進棧,只要棧不爲空,就可以做彈出操作, 每次彈出一個結點,記得把它的左右結點都進棧,記得右子樹先進棧,這樣可以保證右子樹在棧中總處於左子樹的下面。
2.堆棧中存放的是訪問過的結點,就是按照人腦中模擬遍歷二叉樹的方式確定訪問節點的時機,比如先序是遇到即訪問。
後序遍歷模板
常用的:
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> st=new Stack<TreeNode>();
if(root==null) return list;
TreeNode pre=null;
TreeNode cur=root;
while(!st.isEmpty()||cur!=null){
while(cur!=null){
st.push(cur);
cur=cur.left;
}
cur=st.peek();
if(cur.right==null||cur.right==pre){
list.add(cur.val);
pre=cur;
st.pop();
cur=null;
}
else{
cur=cur.right;
}
}
return list;
}
不太常用的
List<Integer> res = new ArrayList<>();
if (root == null) return res;
Stack<TreeNode> stack = new Stack<>();
stack.add(root);
while (!stack.isEmpty()) {
TreeNode node = stack.peek();
if (node.right != null)
stack.add(node.right);
if (node.left != null)
stack.add(node.left);
if (node.left == null && node.right == null) {
node = stack.pop();
res.add(node.val);
while (!stack.isEmpty() && // isParent?
(stack.peek().right == node || stack.peek().left == node)) {
// right child can be null, if stack.peek().left == node, then return from it.
node = stack.pop();
res.add(node.val);
}
}
}
return res;