输入一颗二元查找树,将该树转换为它的镜像,即在转换后的二元查找树中,左子树的结点都大于右子树的结点。用递归和循环两种方法完成树的镜像转换。
分析:
(1)递归的思想很简单:如果左子树和右子树都已经完成了镜像转换,则直接将它们在根节点下的顺序交换一下,整棵树就完成了镜像转换;
(2)循环:问题实际上要将每个节点的孩子的左右顺序交换一下,所以用广度优先的顺序遍历一遍就行,求解过程中需要队列作为辅助数据结构。
#include <iostream>
#include <queue>
using namespace std;
struct BTreeNode
{
BTreeNode* pLeft;
BTreeNode* pRight;
BTreeNode(int _value) {
value = _value;
pLeft = pRight = NULL;
}
int value;
};
void printTree(BTreeNode* root) {
if(root->pLeft != NULL) {
printTree(root->pLeft);
cout << " ";
};
cout << root->value;
if(root->pRight != NULL) {
cout << " ";
printTree(root->pRight);
}
}
/**
* Recursive version.
*/
void doMirrorTransRecursive(BTreeNode* root) {
if(root->pLeft != NULL) doMirrorTransRecursive(root->pLeft);
if(root->pRight != NULL) doMirrorTransRecursive(root->pRight);
BTreeNode* temp = root->pLeft;
root->pLeft = root->pRight;
root->pRight = temp;
}
/**
* Loop version.
*/
void doMirrorTransLoop(BTreeNode* root) {
queue<BTreeNode*> q;
q.push(root);
while(!q.empty()) {
BTreeNode* r = q.front();
q.pop();
if(r->pLeft != NULL) q.push(r->pLeft);
if(r->pRight != NULL) q.push(r->pRight);
BTreeNode* temp = r->pLeft;
r->pLeft = r->pRight;
r->pRight = temp;
}
}
int main() {
// case 1:
BTreeNode* root = new BTreeNode(8);
root->pLeft = new BTreeNode(6);
root->pLeft->pLeft = new BTreeNode(5);
root->pLeft->pRight = new BTreeNode(7);
root->pRight = new BTreeNode(10);
root->pRight->pLeft = new BTreeNode(9);
root->pRight->pRight = new BTreeNode(11);
cout << "Traverse the original tree in mid-order" << endl;
printTree(root);
cout << endl;
cout << "Do mirror transform in recursive style to the original \
tree and traverse the transformed tree (t1) in mid-order" << endl;
doMirrorTransRecursive(root);
printTree(root);
cout << endl;
cout << "Do mirror transform in circularly style to the \
t1 and traverse the transformed in mid-order" << endl;
doMirrorTransLoop(root);
printTree(root);
cout << endl;
return 0;
}