//前序遍历
public void preOrderUnRecur(Node head){
if(head!=null){
Stack<Node> stack = new Stack<Node>();
stack.add(head);
while(!stack.isEmpty()){
head = stack.pop();
System.out.println(head.value+"");
if(head.right!=null){
st.push(head.right);
}
if(head.left!=null){
st.push(head.left);
}
}
}
}
//中序遍历
public void inOrder(TreeNode head){
if(head!=null){
Stack<TreeNode> st = new Stack<TreeNode>();
while(!st.isEmpty()|| head!=null){
if(head!=null){
st.push(head);
head = head.left;
}else{
head = st.pop();
System.out.println(head.value+" ");
head = head.right;
}
}
}
}
//后序遍历
思路:
1.申请一个栈,记为stack,将头结点压入stack,同时设置两个变量h,c;在整个流程中,h代表最近一次弹出并打印的节点,c代表stack的栈顶节点,初始时h为头结点,c为null
2.每次令c等于当前stack的栈顶节点,但是不从stack中弹出,此时分以下三种情况。
1.如果c的左孩子不为null,并且h不等于c的左孩子,也不等于c的右孩子,则把c的左孩子压入stack中。
public void postOrder(TreeNode h){
if(h!=null){
Stack<TreeNode> st = new Stack<TreeNode>();
st.push(h);
Node c = null;
while(!st.isEmpty()){
c = st.peek();
if(c.left!=null &&c.left!=h&&c.right!=h){
st.push(c.left);
}else if(c.right!=null &&h!=c.right){
st.push(c.right);
}else{
System.out.print(st.pop().value+"" );
h = c;
}
}
}
}