层次遍历、中序遍历递归、非递归

层次遍历

使用队列

void  LevelOrder(BiTree T){

    Queue Q;

    Q.add(T);   //加入根节点

    while(!Empty(Q)){

        Y =Q.remove();  // 移除队列头
        System.out.println(Y.data);//访问

        if(Y.leftchild!=null){

            Q.add(Y.leftchild);//左右树不空,放入左右子树根节点,循环

        }

        if(Y.rightchild!=null){

            Q.add(Y.rightchild);

        }

    }

}

中序遍历

递归

void InOrder(BiTree T){

    if(T!=null){
    InOrder(T.leftchild);
    System.out.println(T.data);//访问
    InOrder(T.rightchild);
    }

}

非递归

 利用栈

void InOrder(BiTree T){
    Stack S;
    while(T||!Empty(S)){
        if(T){                //非空  向左走
            S.push(T);
            T = T.leftchild;
        }
        else{
            T = S.pop();        //根退栈 访问 向右走
            System.out.println(T.data);
            T = T.rightchild;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/xyjy11/article/details/82143633