- public void preOrder(){ //非递归前序遍历
- System.out.print("前序遍历: ");
- SeqStack<BinaryNode> stack = new SeqStack<BinaryNode>();
- BinaryNode<E> p = this.root;
- while(p!=null||!stack.isEmpty()){
- if(p!=null){
- System.out.print(p+" ");
- stack.push(p);
- p=p.left;
- }else{
- p=stack.pop().right;
- }
- }
- System.out.println();
- }
- public void inOrder(){ //非递归中序遍历
- System.out.print("中序遍历: " );
- SeqStack<BinaryNode> stack = new SeqStack<BinaryNode>();
- BinaryNode<E> p = this.root;
- while(p!=null||!stack.isEmpty()){
- if(p!=null){
- stack.push(p);
- p=p.left;
- }else{
- p = stack.pop();
- System.out.print(p.data+" ");
- p=p.right;
- }
- }
- System.out.println();
- }
- public void postOrder(){ //非递归后续遍历
- System.out.print("后序遍历: " );
- SeqStack<BinaryNode> stack = new SeqStack<BinaryNode>();
- BinaryNode<E> p = this.root;
- BinaryNode<E> q =null; //记录上一次的访问的结点
- while(p!=null||!stack.isEmpty()){
- while(p!=null){ //一直到最左下的结点
- stack.push(p);
- p=p.left;
- }
- p=stack.get(); //查看栈顶元素
- if(p.right==null||p.right==q){ //如果p没有右孩子或者其右孩子刚刚被访问过
- System.out.print(p.data+" ");
- stack.pop();
- q=p;
- p=null;
- }else {
- p=p.right;
- }
- }
- }
- public void levelOrder(){ //层次遍历 (思想:只读队列里的结点)
- SeqQueue<BinaryNode> queue = new SeqQueue<BinaryNode>();
- System.out.print("层次遍历: ");
- BinaryNode<E> p = this.root;
- while(p!=null||!queue.isEmpty()){
- System.out.print(p.data+" ");
- if(p.left!=null){
- queue.enqueue(p.left);
- }
- if(p.right!=null){
- queue.enqueue(p.right);
- }
- p=queue.dequeue();
- }
- System.out.println();
- }