天天看點

99. 恢複二叉搜尋樹題目描述思路分析代碼實作

99. 恢複二叉搜尋樹

  • 題目描述
  • 思路分析
  • 代碼實作

題目描述

點這裡

思路分析

Morris周遊

99. 恢複二叉搜尋樹題目描述思路分析代碼實作

代碼實作

/**
 * 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) {
        TreeNode *first=NULL,*second,*last=NULL;
        while(root){
            if(!root->left){
                if(last&&last->val>root->val){
                    if(!first) first=last,second=root;
                    else second=root;
                }
                last=root;
                root=root->right;
            }
            else{
                auto p=root->left;
                while(p->right&&p->right!=root) p=p->right;
                if(!p->right) p->right=root,root=root->left;
                else{
                    p->right=NULL;
                    if(last&&last->val>root->val){
                        if(!first) first=last,second=root;
                        else second=root;
                    }
                    last=root;
                    root=root->right;
                }
            }
        }
        swap(first->val,second->val);
    }
};
           

繼續閱讀