栈对二叉树的遍历
package class07;
import java.util.Stack;
/*
*pre pos:弹出打印,压右左/压左右
*in:cur左窜,弹出打印,cur变cur.right
* */
public class UnRecuriveTranversalBT {
public static class Node{
int value;
Node left;
Node right;
public Node(int value){
this.value=value;
}
}
public static void preTraversal(Node head){
//递归改循环;借助栈:
// 弹出就打印
// 有右就右,没有就左
//每个结点是中间:先处理中间,压右左,访问是左右:所以是中左右
if (head==null) return;
Stack<Node> stack =new Stack<Node>();
stack.push(head);
while(!stack.isEmpty()){
head=stack.pop();
System.out.println(head.value);
if(head.right!=null) stack.push(head.right);
if (head.left!=null) stack.push(head.left);
}
}
//每个结点:处理中间,压左右,访问右左:中右左,,,,返过来
public static void posTraversal(Node head){
Stack<Node> stack1=new Stack<Node>();
Stack<Node> stack2=new Stack<Node>();
if(head==null) return;
stack1.push(head);
while(!stack1.isEmpty()){
head=stack1.pop();
stack2.push(head);
System.out.println(head.value);
if(head.left!=null) stack1.push(head.left);
if(head.right!=null) stack1.push(head.right);
}
while(!stack2.isEmpty()) System.out.println(stack2.pop());
}
//底:指针一直串左;弹出打印,指针变右(右空指针中,再中的右)
public static void inTraversal(Node cur){
if (cur==null) return;
Stack<Node> stack=new Stack<Node>();
stack.push(cur);
while(!stack.isEmpty()||cur!=null){//左树完成,cur是根,根弹栈是空,cur又变cur.right
cur=stack.pop();
System.out.println(cur.value);
cur=cur.right;
}
}
}