#include<stdlib.h> #include<stdio.h> #include<stack> #define N 50 using namespace std; typedef struct tree{ char ch; struct tree *lchild; struct tree *rchild; }BitTree; //数组输入 BitTree *CreateTree(int A[], int i, int n){ BitTree *bt; if(i>n) return NULL; else{ bt=(BitTree *)malloc(sizeof(BitTree)); if(A[i]=='#') return NULL; bt->ch=A[i]; bt->lchild=CreateTree(A, 2*i, n); bt->rchild=CreateTree(A, 2*i+1, n); return bt; } } //层次遍历 void LayeredOrderTraverse(BitTree *bt); //交换二叉树中所有结点的左右子树位置 void ExchangeBT(BitTree *bt){ BitTree *QUEUE[N], *temp, *p=bt; int front = 0, rear = 1; if(p != NULL){ QUEUE[0] = p; while(front < rear){ p = QUEUE[front++]; temp = p->lchild; p->lchild = p->rchild; p->rchild = temp; if(p->lchild != NULL) QUEUE[rear++] = p->lchild; if(p->rchild != NULL) QUEUE[rear++] = p->rchild; } } } int main(){ int A[N]={'#','A','B','C','D','E','#','F','G','H'}; BitTree *bt=CreateTree(A,1,9); printf("pre-LayeredOrderTraverse:\n"); LayeredOrderTraverse(bt); printf("\n"); ExchangeBT(bt); printf("post-LayeredOrderTraverse:\n"); LayeredOrderTraverse(bt); return 0; } //层次遍历 void LayeredOrderTraverse(BitTree *bt){ BitTree *QUEUE[N], *p; int front, rear; if(bt != NULL){ QUEUE[0] = bt; front = 0; rear = 1; while(front < rear){ p = QUEUE[front++]; printf("%c ", p->ch); if(p->lchild != NULL) QUEUE[rear++] = p->lchild; if(p->rchild != NULL) QUEUE[rear++] = p->rchild; } } }