层次遍历
使用队列
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;
}
}
}