二叉树的镜像 【微软面试100题 第十五题】

题目要求:

  输入一颗二元查找树(二元搜索树),将该树转换为它的镜像。

  例如:

    8          8

   /   \    --->  /  \

  6      11      11    6

  参考资料:剑指offer第20题

题目分析:

  思路很简单:从根结点开始,交换左右结点的值,同时递归的处理左右子树。

  代码中打印二叉树用到了分层遍历二叉树,见编程之美3.10.

代码实现:

#include <iostream>
#include <queue>

using namespace std;

typedef struct BinaryTree
{
    struct BinaryTree *left,*right;
    int data;
}BinaryTree;

void initTree(BinaryTree **p);
void MirrorRecursively(BinaryTree *root);
void PrintTreeByLevel(BinaryTree *root);

int main(void)
{
    BinaryTree *root;
    initTree(&root);
    cout << "原二叉树:" << endl;
    PrintTreeByLevel(root);
    MirrorRecursively(root);
    cout << endl;
    cout << "镜像后的二叉树:" << endl;
    PrintTreeByLevel(root);
    return 0;
}
//分层遍历二叉树,见编程之美3.10
void PrintTreeByLevel(BinaryTree *root)
{
    if(root==NULL)
        return;
    queue<BinaryTree *> Q;
    Q.push(root);
    Q.push(0);
    while(!Q.empty())
    {
        BinaryTree *tmp = Q.front();
        Q.pop();
        if(tmp)
        {
            cout << tmp->data << " ";
            if(tmp->left)
                Q.push(tmp->left);
            if(tmp->right)
                Q.push(tmp->right);
        }
        else if(!Q.empty())
        {
            Q.push(0);
            cout << endl;
        }
    }
}
void MirrorRecursively(BinaryTree *root)
{
    if(root == NULL)
        return;
    if(root->left == NULL || root->right == NULL)
        return;

    BinaryTree *tmp = root->left;
    root->left = root->right;
    root->right = tmp;

    if(root->left)
        MirrorRecursively(root->left);
    if(root->right)
        MirrorRecursively(root->right);
}
//      10
//     / \
//    5   12
//   / \
//  4   7
void initTree(BinaryTree **p)
{
    *p = new BinaryTree;
    (*p)->data = 10;
 
    BinaryTree *tmpNode = new BinaryTree;
    tmpNode->data = 5;
    (*p)->left = tmpNode;
 
    tmpNode = new BinaryTree;
    tmpNode->data = 12;
    (*p)->right = tmpNode;
    tmpNode->left = NULL;
    tmpNode->right = NULL;
 
    BinaryTree *currentNode = (*p)->left;
 
    tmpNode = new BinaryTree;
    tmpNode->data = 4;
    currentNode->left = tmpNode;
    tmpNode->left = NULL;
    tmpNode->right = NULL;
 
    tmpNode = new BinaryTree;
    tmpNode->data = 7;
    currentNode->right = tmpNode;
    tmpNode->left = NULL;
    tmpNode->right = NULL;
 
}
View Code

 

posted on 2014-10-28 16:38  tractorman  阅读(189)  评论(0编辑  收藏  举报

导航