• [LeetCode]Recover Binary Search Tree


    题目描述:(链接)

    Two elements of a binary search tree (BST) are swapped by mistake.

    Recover the tree without changing its structure.

    Note:
    A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?

    解题思路:

    空间复杂度是O(n), 利用中序遍历,将节点保存在一个数组中,然后遍历数组,找出错位的两个节点,交换值。

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     void recoverTree(TreeNode* root) {
    13         vector<TreeNode *> cache1;
    14         stack<TreeNode *> cache2;
    15         TreeNode *p = root;
    16         
    17         while (!cache2.empty() || p != nullptr) {
    18             if (p != nullptr) {
    19                 cache2.push(p);
    20                 p = p->left;
    21             } else {
    22                 p = cache2.top();
    23                 cache2.pop();
    24                 cache1.push_back(p);
    25                 p = p->right;
    26             }
    27         }
    28         
    29         int len = cache1.size();
    30         TreeNode *first;
    31         for (int i = 0; i < len - 1; ++i) {
    32             TreeNode *tmp1 = cache1[i];
    33             TreeNode *tmp2 = cache1[i + 1];
    34             if (tmp1->val > tmp2->val) {
    35                 first = tmp1;
    36                 break;
    37             }
    38         }
    39         
    40         TreeNode *second;
    41         for (int i = len - 1; i > 0; --i) {
    42             TreeNode *tmp1 = cache1[i];
    43             TreeNode *tmp2 = cache1[i - 1];
    44             if (tmp1->val < tmp2->val) {
    45                 second = tmp1;
    46                 break;
    47             }
    48         }
    49         
    50         if (first != nullptr && second != nullptr) {
    51             swap(first->val, second->val);
    52         }
    53     }
    54 };
  • 相关阅读:
    python基础篇-wordcloud库的使用
    python基础篇-数据格式化和处理
    python基础篇-文件(读取,操作,关闭)
    python基础篇-jieba库的使用
    python基础篇-组合数据类型-3.字典
    mbStringLength 获取javascript字符串字节数
    JS 字符unicode转换函数
    jar命令解析--转自百度知道
    JBOSS7.0 热部署及开启远程调试的方法
    WampServer 安装心得
  • 原文地址:https://www.cnblogs.com/skycore/p/5011060.html
Copyright © 2020-2023  润新知