1 //二叉树的先序遍历(非递归) 2 public void PreOrderTraverse() 3 { 4 BiTNode p = this.root; 5 Stack stack = new Stack(10000); 6 7 while(!stack.isEmpty || p != null) 8 if(p != null) 9 { 10 if(p.rchild != null) 11 stack.push(p.rchild); 12 System.out.print(p.data + " "); 13 p = p.lchild; 14 } 15 else 16 { 17 p = stack.pop(); 18 } 19 } 20 21 //二叉树的中序遍历(非递归) 22 public void InOrderTraverse() 23 { 24 BiTNode p = this.root; 25 Stack stack = new Stack(10000); 26 27 while(!stack.isEmpty() || p != null) 28 if(p != null) 29 { 30 stack.push(p); 31 p = p.child; 32 } 33 else 34 { 35 p = stack.pop(); 36 System.out.print(p.data + " "); 37 p = p.lchild; 38 } 39 }
1 //二叉树的后序遍历(非递归) 2 public void PostOrderTraverse() 3 { 4 BiNode p = this.root; 5 Stack stack = new Stack(10000); 6 7 while(true) 8 { 9 if(p != null) 10 { 11 if(p.count == 0) 12 { 13 stack.push(p); 14 p = p.lchild; 15 } 16 else if(p.count == 1) 17 p = p.rchild; 18 else if(p.count == 2) 19 { 20 System.out.print(stack.pop().data + " "); 21 if(!stack.isEmpty()) 22 { 23 p = stack.getTop(); 24 p.count++; 25 } 26 else 27 break; //栈为空(根结点已出栈) 28 } 29 } 30 else //p = null 31 { 32 p = stack.getTop(); 33 p.count++; 34 if(p.count == 1) 35 p = p.rchild; 36 else if(p.count == 2) 37 { 38 System.out.print(stack.pop().data + " "); 39 if(!stack.isEmpty()) 40 { 41 p = stack.getTop(); 42 p.count++; 43 } 44 else 45 break; //栈为空(根结点已出栈) 46 } 47 } 48 } //while 49 }
原文地址:https://www.cnblogs.com/Huayra/p/10747676.html
时间: 2024-10-06 14:22:48