题目:输入一棵二元查找树,将该树转换为它的镜像,即在转换后的二元查找树中,左子树的结点都大于右子树的结点。
要求:用递归和循环两种方法完成树的镜像转换。
举例:
8 8 / \ 转换 / \ 6 10 --> 10 6 / \ / \ / \ / \ 5 7 9 11 11 9 7 5
#include <iostream> #include <cstdio> #include <cstdlib> #include <queue> #include <stack> using namespace std; typedef struct node { int key; struct node *pleft; struct node *pright; }Node; int CreateTreeByInsertData(Node **p,int k)//理解为什么用二级指针 { if(*p==NULL) { *p=(Node *)malloc(sizeof(Node)); (*p)->key=k; (*p)->pleft=(*p)->pright=NULL; return 1; } else if(k == (*p)->key) return 0; else if(k < (*p)->key) return CreateTreeByInsertData(&(*p)->pleft,k); else return CreateTreeByInsertData(&(*p)->pright,k); } void swap(Node **l, Node **r) { Node *p = *l; *l = *r; *r = p; } void mirror(Node *root)//递归来使得镜像对称 { if(root == NULL) return; swap( &(root->pleft), &(root->pright)); mirror(root->pleft); mirror(root->pright); } void mirrorByStack(Node *root)//用栈来做得镜像对称 { stack<Node *>myStack; if(root == NULL) return; myStack.push(root); while(!myStack.empty()) { Node *p = myStack.top();//取得栈顶元素 myStack.pop();//只是弹出,删除,并不能取到栈顶元素 swap( &(p->pleft), &(p->pright)); if(p->pleft!=NULL) myStack.push(p->pleft); if(p->pright!=NULL) myStack.push(p->pright); } } void visitByLevel(Node *p)//层次遍历,上到下,左到右 { queue<Node*> myQueue; if(p == NULL) return; myQueue.push(p); while(!myQueue.empty()) { Node *now = myQueue.front(); myQueue.pop(); printf("%d ",now->key); if(now->pleft) myQueue.push(now->pleft); if(now->pright) myQueue.push(now->pright); } printf("\n"); } void ClearTree(Node** tree)//删除树的操作,在本题中不一定用的到 { if(*tree==NULL)return; ClearTree(&(*tree)->pleft); ClearTree(&(*tree)->pright); free(*tree); *tree=NULL; } int main() { int i; Node *proot = NULL; int data[] = {8,6,10,5,7,9,11}; //依次插入一些数据,创建一个二叉排序树 for(i=0; i<sizeof(data)/sizeof(int); i++) CreateTreeByInsertData(&proot, data[i]); visitByLevel(proot);//8 6 10 5 7 9 11 mirror(proot); visitByLevel(proot);//8 10 6 11 9 7 5 mirrorByStack(proot); visitByLevel(proot);//8 6 10 5 7 9 11 ClearTree(&proot); return 0; }