99. Recover Binary Search Tree

Posted 为了更优秀的你,加油!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了99. 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?

解题思路:本题主要是考查了Morris Traversal,一种根据线索二叉树思想的时间复杂度为O(n),空间复杂度为O(1)的中序遍历方式。

在博客http://www.cnblogs.com/AnnieKim/archive/2013/06/15/MorrisTraversal.html里,原作者对Morris Traversal说的很明白。此题在此基础上只要比较相邻两个数的大小,就可以确定哪两个是打乱序的了。而Morris Traversal的中序输出就是原数组的从小到大排序,因而一切就变得简单了

/**
 * 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) {
        TreeNode *pre=NULL,*cur=root;
        TreeNode *first=NULL,*second=NULL,*temp=NULL;
        while(cur!=NULL){
            if(cur->left==NULL){
                //cur->val;
                if(temp!=NULL&&temp->val>cur->val){
                    if(!first)first=temp;
                    second=cur;
                }
                temp=cur;
                cur=cur->right;
            }
            else {
                pre=cur->left;
                while(pre->right!=NULL&&pre->right!=cur)
                pre=pre->right;
                //exist threaded tree
                if(pre->right==cur){
                    //print cur->val;
                    if(temp!=NULL&&temp->val>cur->val){
                        if(!first)first=temp;
                        second=cur;
                    }
                    temp=cur;
                    pre->right=NULL;
                    cur=cur->right;
                }
                //creating backend poinner to the current point
                else{
                    pre->right=cur;
                    cur=cur->left;
                }
            }
        }
        swap(first->val,second->val);
    }
};

 

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

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