• 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?

    /**
     * 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);
        }
    };
  • 相关阅读:
    Java实现第八届蓝桥杯字母组串
    Java实现第八届蓝桥杯正则问题
    Java实现第八届蓝桥杯方格分割
    Java实现第八届蓝桥杯方格分割
    经典SQL语句大全(绝对的经典)
    SQL脚本
    非常有用的sql脚本
    代码生成器实现的Entity,Dao,Service,Controller,JSP神器(含代码附件)
    搭建MySQL高可用负载均衡集群
    MySQL——修改root密码的4种方法(以windows为例)
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759585.html
Copyright © 2020-2023  润新知