码迷,mamicode.com
首页 > 其他好文 > 详细

99. Recover Binary Search Tree

时间:2017-02-21 21:52:21      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:forward   arc   bst   比较   基础   大小   blog   ons   ini   

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

标签:forward   arc   bst   比较   基础   大小   blog   ons   ini   

原文地址:http://www.cnblogs.com/tsunami-lj/p/6426342.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!