LeetCode 99. 恢复二叉搜索树

题目描述链接:https://leetcode-cn.com/problems/recover-binary-search-tree/

解题思路:中序遍历二叉树,找出不符合条件的两个节点,然后重新遍历进行恢复

LeetCode C++求解代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void recoverTree(TreeNode* root) {

        stack<TreeNode *>S;
        TreeNode* p=root;
        TreeNode* q;
        vector<int>res;
        while(!S.empty()||p){
            if(p){
                S.push(p);
                p=p->left;
            }
            else{
               q=S.top();
               S.pop();
               res.push_back(q->val);
               p=q->right;
            }
        }
        int x=-1,y=-1;
        for(int i=0;i<res.size()-1;++i){
            if(res[i+1]<res[i]){
                y=res[i+1];
                if(x==-1){
                    x=res[i];
                }
                else{
                    break;
                }
            }
        }
     recover(root,2,x,y);

    }
      
   void recover(TreeNode *root,int count,int x,int y){
        if(root){
            
            if(root->val==x){

                root->val=y;
                count--;
               
            }
            else  if(root->val==y){

                root->val=x;
                count--;
               
            }
            if(count==0){
                return ;
            }


            recover(root->left,count,x,y);
            recover(root->right,count,x,y);
        }
    }





};

时间复杂度:O(n)   空间复杂度O(n)

原文地址:https://www.cnblogs.com/zzw-/p/13460240.html