二叉树非递归遍历(前序,中序,后续遍序)

 

Code:
  1. public void preOrder(){  //非递归前序遍历  
  2.         System.out.print("前序遍历: ");  
  3.         SeqStack<BinaryNode> stack = new SeqStack<BinaryNode>();  
  4.         BinaryNode<E> p = this.root;  
  5.           
  6.         while(p!=null||!stack.isEmpty()){  
  7.             if(p!=null){  
  8.                 System.out.print(p+" ");  
  9.                 stack.push(p);  
  10.                 p=p.left;  
  11.             }else{  
  12.                 p=stack.pop().right;  
  13.             }  
  14.         }  
  15.         System.out.println();  
  16.     }  
  17.       
  18.       
  19.     public void inOrder(){  //非递归中序遍历  
  20.         System.out.print("中序遍历: " );  
  21.         SeqStack<BinaryNode> stack = new SeqStack<BinaryNode>();  
  22.         BinaryNode<E> p = this.root;  
  23.           
  24.         while(p!=null||!stack.isEmpty()){  
  25.             if(p!=null){  
  26.                 stack.push(p);  
  27.                 p=p.left;  
  28.             }else{  
  29.                 p = stack.pop();  
  30.                 System.out.print(p.data+" ");  
  31.                 p=p.right;  
  32.             }  
  33.         }  
  34.         System.out.println();  
  35.     }  
  36.       
  37.     public void postOrder(){   //非递归后续遍历   
  38.         System.out.print("后序遍历: " );   
  39.         SeqStack<BinaryNode> stack = new SeqStack<BinaryNode>();  
  40.         BinaryNode<E> p = this.root;  
  41.         BinaryNode<E> q =null;  //记录上一次的访问的结点  
  42.           
  43.         while(p!=null||!stack.isEmpty()){  
  44.             while(p!=null){   //一直到最左下的结点  
  45.                 stack.push(p);  
  46.                 p=p.left;  
  47.             }  
  48.             p=stack.get();  //查看栈顶元素  
  49.             if(p.right==null||p.right==q){      //如果p没有右孩子或者其右孩子刚刚被访问过  
  50.                 System.out.print(p.data+" ");  
  51.                 stack.pop();  
  52.                 q=p;  
  53.                 p=null;  
  54.             }else {  
  55.                 p=p.right;  
  56.             }  
  57.               
  58.         }  
  59.     }  
  60.   
  61.       
  62.     public void levelOrder(){  //层次遍历 (思想:只读队列里的结点)  
  63.         SeqQueue<BinaryNode> queue = new SeqQueue<BinaryNode>();  
  64.         System.out.print("层次遍历: ");  
  65.         BinaryNode<E> p = this.root;  
  66.           
  67.         while(p!=null||!queue.isEmpty()){  
  68.             System.out.print(p.data+" ");  
  69.             if(p.left!=null){  
  70.                 queue.enqueue(p.left);  
  71.             }  
  72.             if(p.right!=null){  
  73.                 queue.enqueue(p.right);  
  74.             }  
  75.             p=queue.dequeue();  
  76.         }  
  77.         System.out.println();  
  78.     }  

 

你可能感兴趣的:(null)