非递归先,中,后遍历二叉树

1:后序遍历二叉树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//后序遍历二叉树,在函数中改变了树T,可以在函数中对原树T进行复制然后处理复制树或者加些辅助结构
public  static  void  InOrderTraverse(Tree T,Tree r){
             Stake stake =  new  Stake(); //栈
             stake.push(T);
             Tree tem = T;
              
             while (!stake.isEmpty()){
                 while (tem!= null  && tem.lchild !=  null ){ //向左走到尽头,等于访问根的左子树=null
                     stake.push(tem.lchild);
                     tem = tem.lchild;
                 }
                  
                 tem = tem.rchild; //访问右子树
                 if (tem !=  null )stake.push(tem);
                 else {
              //一个节点的左子树和右子树都为null的情况,即表明该根节点的左右子树均已经被访问过了,现在访问根节点
                    tem = stake.pop();
                    System.out.print(tem.ele+ " " ); //访问根节点
                    
                    tem = stake.peek();
                    
                    if (tem ==  null return ; //遍历结束
                    
                    if (tem.lchild !=  null )tem.lchild =  null ; //如果左子树被访问,设置其左为null,在此处改变了树
                    else  tem.rchild =  null ; //同理,设置其右为null
                 }
             }
       }

2:先序和中序遍历二叉树

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
//非递归方法遍历二叉树,中序遍历
     public  static  void  InOrderTraverse(Tree T){
         Stake stake =  new  Stake();
         stake.push(T);
         Tree tem = T;
         
         while (!stake.isEmpty()){
             while (tem!= null  && tem.lchild !=  null ){ //向左走到尽头
                 stake.push(tem.lchild);
                 tem = tem.lchild;
             }
             
             tem = stake.pop();
             System.out.print(tem.ele+ " " ); //访问根节点
             
             tem = tem.rchild; //访问右子树
             if (tem !=  null )stake.push(tem);
         }
     }
     
     //非递归方法遍历二叉树二
         public  static  void  InOrderTraverse2(Tree T){
             Stake stake =  new  Stake(); //栈道
             //stake.push(T);
             Tree tem = T;
             boolean  flag =  true ;
             
             while (flag || !stake.isEmpty()){
                 flag =  false ;
                 
                 if (tem !=  null ){
                     System.out.println(tem.ele+ " " ); //先序遍历法
                     stake.push(tem); tem = tem.lchild; //遍历左子树
                 }
                 else {
                     tem = stake.pop();
                     //System.out.print(tem.ele+" ");//中序遍历法访问根节点
                     tem = tem.rchild; //遍历右子树
                 }
             }
         }
    

你可能感兴趣的:(数据结构与算法,非递归遍历二叉树,二叉树,遍历二叉树)