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

来源:互联网 发布:mcu选型软件 编辑:程序博客网 时间:2024/05/01 23:16

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<Tree> stake = new Stake<Tree>();//栈
            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 == nullreturn;//遍历结束
                    
                   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<Tree> stake = new Stake<Tree>();
        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<Tree> stake = new Stake<Tree>();//栈道
            //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;//遍历右子树
                }
            }
        }
    

0 0
原创粉丝点击