二叉树的镜像 【微软面试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   tractorman  阅读(192)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

导航

统计

点击右上角即可分享
微信分享提示