99. Recover Binary Search Tre

Posted 积少成多

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了99. Recover Binary Search Tre相关的知识,希望对你有一定的参考价值。

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?

=============

解法:来自leetcode 150题集

O(n)的解法,开一个指针数组,中序遍历,将节点指针一次存放在数组中,

然后寻找两处逆向的位置,先从前往后找第一个逆序的位置,然后从后往前寻找第二个逆序的位置,交换两个指针的值,

递归/非递归中序遍历一般需要用到栈,空间也是O(n)的,可以利用morris中序遍历的方式

=====

code:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    ///
    void recoverTree(TreeNode *root){
        pair<TreeNode *,TreeNode *> broken;
        TreeNode *curr = root;
        TreeNode *prev = nullptr;
        broken.first = broken.second = nullptr;

        while(curr!=nullptr){
            if(curr->left==nullptr){
                detect(broken,prev,curr);
                prev = curr;
                curr = curr->right;
            }else{
                auto node = curr->left;
                ///prev = curr->left;
                while(node->right != nullptr && node->right!=curr){
                    node = node->right;
                }

                ///find predecessor
                if(node->right==nullptr){
                    node->right = curr;
                    curr = curr->left;
                }else{
                    node->right = nullptr;
                    detect(broken,prev,curr);
                    prev = curr;
                    curr = curr->right;
                }
            }///if-else
        }///while

        swap(broken.first->val,broken.second->val);
    }
    void detect(pair<TreeNode *,TreeNode *> &broken,TreeNode *prev,
        TreeNode *curr){
        if(prev!=nullptr && prev->val > curr->val){
            if(broken.first == nullptr) broken.first = prev;
            broken.second = curr;
        }
    }
};

 

以上是关于99. Recover Binary Search Tre的主要内容,如果未能解决你的问题,请参考以下文章

99. Recover Binary Search Tree

LeetCode99 Recover Binary Search Tree

99. Recover Binary Search Tree

Leetcode 99. Recover Binary Search Tree

Leetcode 99. Recover Binary Search Tree

LeetCode OJ 99. Recover Binary Search Tree