zoukankan      html  css  js  c++  java
  • 面试题20:搜索二叉树可能有两个元素发生了交换,如何恢复BST?

    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

     1 /**
     2  * Definition for binary tree
     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     TreeNode* pre = nullptr;
    13     TreeNode* mistake1 = nullptr;
    14     TreeNode* mistake2 = nullptr;
    15     void recoverTree(TreeNode *root) {
    16         inorder(root);
    17         if(mistake1 && mistake2) swap(mistake1->val,mistake2->val);
    18     }
    19     void inorder(TreeNode* root){
    20         if(root == nullptr) return ;
    21         inorder(root->left);
    22         if(pre == nullptr) pre = root;
    23         else{
    24             if(pre->val > root->val){
    25                 if(mistake1 == nullptr) mistake1=pre;
    26                 mistake2 = root;
    27             }
    28             pre = root;
    29         }
    30         inorder(root->right);
    31     }
    32 };
  • 相关阅读:
    萨卡斯指法
    香港保险
    数据分析,了解行业
    数据分析师
    黑盒测试方法
    web系统的常用功能测试
    linux-磁盘问题
    mysql连表查询
    mysql模糊查询
    MySQL 数据类型
  • 原文地址:https://www.cnblogs.com/wxquare/p/6864142.html
Copyright © 2011-2022 走看看