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?
二叉树遍历方式:前序,后序,中序
后序:先左右后根——[3, 2, 1]
前序:先根后左右——[1, 2, 3]
中序:左中右——[1, 3, 2]
使用栈迭代
前序最简单,应该先push根,再pop根,根据根的叶子,先push右,再push左
后序的话,应该先push根,然后push右,再push左,push叶子时要断开根和叶子的关联,因为后面我出栈的设定为无叶子节点进行pop
中序的话,取出根,因为我需要按照右叶子——根——左叶子这个流程push,同理,push叶子过程中取消根和叶子的关系,后面判断无叶子时进行pop
package leetCode;
import java.util.ArrayList;
import java.util.Stack;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int val){
this.val = val;
}
}
class my0620{
//前序 1 3 8 5 4 9
public static ArrayList<Integer> postorderTraversa1(TreeNode root){
Stack<TreeNode> treeStack = new Stack<TreeNode>();
ArrayList<Integer> ret = new ArrayList<Integer>();
if(root == null){
return ret;
}
treeStack.push(root);
while(!treeStack.isEmpty()){
TreeNode cur = treeStack.pop();
ret.add(cur.val);
if(cur.right != null){
treeStack.push(cur.right);
}
if(cur.left != null){
treeStack.push(cur.left);
}
}
return ret;
}
//后序 8 3 4 9 5 1
public static ArrayList<Integer> postorderTraversa2(TreeNode root){
Stack<TreeNode> treeStack = new Stack<TreeNode>();
ArrayList<Integer> ret = new ArrayList<Integer>();
if(root == null){
return ret;
}
treeStack.push(root);
while(!treeStack.isEmpty()){
TreeNode cur = treeStack.peek();
if(cur.right == null && cur.left == null){
treeStack.pop();
ret.add(cur.val);
continue;
}
if(cur.right != null){
treeStack.push(cur.right);
cur.right = null;
}
if(cur.left != null){
treeStack.push(cur.left);
cur.left = null;
}
}
return ret;
}
//中序 3 8 1 4 5 9
public static ArrayList<Integer> postorderTraversa3(TreeNode root){
Stack<TreeNode> treeStack = new Stack<TreeNode>();
ArrayList<Integer> ret = new ArrayList<Integer>();
if(root == null){
return ret;
}
treeStack.push(root);
while(!treeStack.isEmpty()){
TreeNode cur = treeStack.pop();
if(cur.left == null && cur.right == null){
ret.add(cur.val);
continue;
}
if(cur.right != null){
treeStack.push(cur.right);
cur.right = null;
}
treeStack.push(cur);
if(cur.left != null){
treeStack.push(cur.left);
cur.left = null;
}
}
return ret;
}
}
/*
1
/ \
3 5
/ \ / \
8 4 9
*/
public class postTraversal {
public static void main(String []args){
TreeNode n11 = new TreeNode(1);
TreeNode n21 = new TreeNode(3);
TreeNode n22 = new TreeNode(5);
TreeNode n32 = new TreeNode(8);
TreeNode n33 = new TreeNode(4);
TreeNode n34 = new TreeNode(9);
n11.left = n21;
n11.right = n22;
n21.right = n32;
n22.left = n33;
n22.right = n34;
//System.out.println(my0620.postorderTraversa1(n11));
//System.out.println(my0620.postorderTraversa2(n11));
System.out.println(my0620.postorderTraversa3(n11));
}
}