ProDeveloperTutorial.com

教程和编程解决方案
菜单
  • Shell脚本
  • 系统设计
  • Linux系统编程
  • 4g LTE
  • 编码问题
  • C
  • C ++
  • DSA
  • GIT

将二叉树转换为其镜像树

前开发者教程 2020年10月8日

题:

给定一个二叉树根节点,将该树转换为它’s mirror.

例:

考虑下面给出的图像及其镜像。

将二叉树转换为其镜像树

上图显示了一棵树和它’s mirror tree.

从上图可以看到,除了根节点之外,所有其他节点都从右到左或从左到右更改。

例如:

节点b已离开,它已更改为镜像树中的右侧节点
节点c正确,它已更改为镜像树中的左侧节点

同样的

节点d已离开,它已更改为镜像树中的右侧节点
节点e正确,它已更改为镜像树中的左侧节点

所以这就是我们可以将二叉树转换为其镜像的方法

C ++解决方案

#include <iostream>
#include <queue>
#include <stack>
using namespace std;

// structure to hold binary tree node
struct Node
{
    int data;
    Node *left, *right;

    Node(int data)
    {
        this->data = data;
        this->left = this->right = nullptr;
    }
};

void inorder(Node *node) 
{
    if(node == NULL) 
    {
      return;
    }
    
    inorder(node->left);
    cout<< node->data << " ";
    inorder(node->right);
}

Node * convert_mirror_tree(Node *node) 
{
    if(node == NULL) 
    {
      return NULL;
    }
    
    Node *temp = node->left;
    node->left = node->right;
    node->right = temp;
    
    convert_mirror_tree(node->left);
    convert_mirror_tree(node->right);
    
    return node;
}

int main()  
{  
    Node* root = nullptr;
    /* Binary tree:
              16
            /   \
           /     \
          10      25
         /  \    /  \
        /    \  /    \
       7    15 18     30

    */

    root = new Node(16);
    root->left = new Node(10);
    root->right = new Node(25);
    root->left->left = new Node(7);
    root->left->right = new Node(15);
    root->right->left = new Node(18);
    root->right->right = new Node(30);

    cout<<"Before convert inorder traversal = "<<endl;
    inorder(root);
    cout<<endl;

    Node *result = convert_mirror_tree(root);
    cout<<"After convert inorder traversal = "<<endl;
    inorder(root);
    cout<<endl;

    return 0;  
}  

输出:

Before convert inorder traversal =
7 10 15 16 18 25 30
After convert inorder traversal =
30 25 18 16 15 10 7

 

 

分享
电子邮件
鸣叫
领英
Reddit
绊倒
Pinterest的
上一篇文章
下一篇

关于作者

前开发者教程

每天我们都会讨论竞争性编程问题,请加入我们的网站:   电报频道

ProDeveloperTutorial.com

教程和编程解决方案
版权© 2020 ProDeveloperTutorial.com
从以下课程获得热门课程: 教育性的
    <aside id="LeAoFbi" class="LDhZWxx"><address id="k2h6I2W"><area class="c3my6Fr"></area></address></aside>



    <ins class="fTOopdj"><ul class="BkUfsIX"></ul></ins>


  1. <noscript id="wGirUv9"><ins id="Gqd7ywR" class="GMNPMPT"></ins></noscript>