zoukankan      html  css  js  c++  java
  • [何海涛] 求二元查找树的镜像

    题目:输入一颗二元查找树,将该树转换为它的镜像,即在转换后的二元查找树中,左子树的结点都大于右子树的结点。用递归和循环两种方法完成树的镜像转换。

    例如输入:

         8
        /  \
      6      10
     /\       /\
    5  7    9   11

    输出:

          8
        /  \
      10    6
     /\      /\
    11  9  7  5

    递归或者栈模拟

     1 #include <iostream>
     2 #include <stack>
     3 using namespace std;
     4 
     5 struct Node
     6 {
     7     int val;
     8     Node *left;
     9     Node *right;
    10     Node():left(NULL), right(NULL){}
    11 };
    12 
    13 void convert(Node *root)
    14 {
    15     if (root == NULL)
    16         return;
    17 
    18     convert(root->left);
    19     convert(root->right);
    20     Node *node = root->left;
    21     root->left = root->right;
    22     root->right = node;
    23 }
    24 
    25 void stackConvert(Node *root)
    26 {
    27     stack<Node* > s;
    28     s.push(root);
    29 
    30     while(!s.empty())
    31     {
    32         Node *node = s.top();
    33         s.pop();
    34 
    35         Node *temp = node->left;
    36         node->left = node->right;
    37         node->right = temp;
    38 
    39         if (node->left)
    40             s.push(node->left);
    41         if (node->right)
    42             s.push(node->right);
    43     }
    44 }
    45 
    46 void print(Node *node)
    47 {
    48     if (node == NULL)
    49         return;
    50 
    51     cout << "Node:" << node << " val:" << node->val << " left:" << node->left << " right:" << node->right << endl;
    52 
    53     print(node->left);
    54     print(node->right);
    55 }
    56 
    57 int main()
    58 {
    59     Node node[7];
    60     node[0].val = 8;
    61     node[0].left = &node[1];
    62     node[0].right = &node[2];
    63 
    64     node[1].val = 6;
    65     node[1].left = &node[3];
    66     node[1].right = &node[4];
    67 
    68     node[2].val = 10;
    69     node[2].left = &node[5];
    70     node[2].right = &node[6];
    71 
    72     node[3].val = 5;
    73     node[4].val = 7;
    74     node[5].val = 9;
    75     node[6].val = 11;
    76 
    77     //convert(&node[0]);
    78     stackConvert(&node[0]);
    79 
    80     print(&node[0]);
    81     cout << endl;
    82 
    83     Node a[2];
    84     a[0].val = 1;
    85     a[0].left = &a[1];
    86 
    87     a[1].val = 2;
    88 
    89     //convert(&a[0]);
    90     stackConvert(&a[0]);
    91     print(&a[0]);
    92 }
  • 相关阅读:
    在阿里云“专有网络”网络类型中配置vsftpd
    Ubuntu 16.04下开启Mysql 3306端口远程访问
    .net core 2.0 报错:error NU1102: Unable to find package ...
    .NET Core Runtime ARM32 builds now available
    .NET Core on Raspberry Pi
    .NET Core 跨平台发布(dotnet publish)
    使用vscode开发调试.net core应用程序并部署到Linux跨平台
    docker容器镜像删除
    使用阿里docker镜像加速器加速
    树莓派3b基于UbuntuMate下载中文输入法
  • 原文地址:https://www.cnblogs.com/chkkch/p/2781381.html
Copyright © 2011-2022 走看看