先序遍历
void PreorderTraversal( BinTree BT ){
if (BT){
printf(" %c",BT->Data);
PreorderTraversal(BT->Left);
PreorderTraversal(BT->Right);
}
}
中序遍历
void InorderTraversal( BinTree BT ){
if (BT){
InorderTraversal(BT->Left);
printf(" %c",BT->Data);
InorderTraversal(BT->Right);
}
}
后序遍历
void PostorderTraversal( BinTree BT ){
if (BT){
PostorderTraversal(BT->Left);
PostorderTraversal(BT->Right);
printf(" %c",BT->Data);
}
}
层次遍历
(数组实现)
void LevelorderTraversal( BinTree BT ){
if (BT){
BinTree Q[100];
BinTree p;
int head=0,tail=0;
if (BT){
Q[tail++]=BT;
while (tail!=head){
p=Q[head++];
printf(" %c",p->Data);
if (p->Left) Q[tail++]=p->Left;
if (p->Right) Q[tail++]=p->Right;
}
}
}
}
(队列实现)
void LevelOrder(Node *root) {
if(root == NULL) return;
queue<Node*> Q;
Q.push(root);
//while there is at least one discovered node
while(!Q.empty()) {
Node* current = Q.front();
Q.pop(); // removing the element at front
cout<<current->data<<" ";
if(current->left != NULL) Q.push(current->left);
if(current->right != NULL) Q.push(current->right);
}
}