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

Recover Binary Search Tree

时间:2014-06-03 13:53:21      阅读:309      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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?

bubuko.com,布布扣
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    void swap(int& a,int&b)
    {
        int tmp=a;
        a=b;
        b=tmp;
    }
    TreeNode* findlarge(TreeNode* root,int val)
    {
        if(root==NULL) return NULL;
        TreeNode* result=NULL;
        if(root->val>val) 
        {
            val=root->val;
            result=root;
        }
        TreeNode* p1=findlarge(root->left,val);
        TreeNode* p2=findlarge(root->right,val);
        if(p1!=NULL) result=p1;
        if(p2!=NULL)
        {
            if(result==NULL) result=p2;
            else 
                if(result->val<p2->val) result=p2;
        }
        return result;
    }    
    TreeNode* findsmall(TreeNode* root,int val)
    {
        if(root==NULL) return NULL;
        TreeNode* result=NULL;
        if(root->val<val) 
        {
            val=root->val;
            result=root;
        }
        TreeNode* p1=findsmall(root->left,val);
        TreeNode* p2=findsmall(root->right,val);
        if(p1!=NULL) result=p1;
        if(p2!=NULL)
        {
            if(result==NULL) result=p2;
            else 
                if(result->val>p2->val) result=p2;
        }
        return result;
    }
public:
    void recoverTree(TreeNode *root) 
    {
        if(root==NULL) return;
        TreeNode* left=findlarge(root->left,root->val);
        TreeNode* right=findsmall(root->right,root->val);
        if(left!=NULL && right!=NULL)
        {        
            swap(left->val,right->val);
            return;
        }
        if(right!=NULL)
        {
            swap(root->val,right->val);
            return;
        }
        if(left!=NULL)
        {
            swap(root->val,left->val);
            return;
        }
        recoverTree(root->left);
        recoverTree(root->right);
    }
};
bubuko.com,布布扣

 

Recover Binary Search Tree,布布扣,bubuko.com

Recover Binary Search Tree

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/erictanghu/p/3759585.html

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