• [何海涛] 求二元查找树的镜像


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

    例如输入:

         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 }
  • 相关阅读:
    Hello World基于.net framework中CLR的执行
    MVN常用命令
    Git常用命令
    Markdown常用语法
    计算机专用英语词汇
    Windows DiskPart
    字符集过滤器
    SSHkey
    书名
    redis
  • 原文地址:https://www.cnblogs.com/chkkch/p/2781381.html
Copyright © 2020-2023  润新知