C++ BST


  • 0
    B

    class Solution {
    public:

    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
        unordered_map<int,Node*> map;
        int i=0;
        while(i<nums.size())
        {
            if(i>k)root=delete_Node(root,i-k-1,nums[i-k-1]);
            root=insert(root,i,nums[i],k,t);
            if(result)return true;
            i++;
        }
        return result;
    }
    Node* insert(Node* node,long key,long val,int k,int t)
    {
        if(node && abs(node->val-val)<=t && key-node->key<=k)result=true;
        if(!node)
        {
            node=new Node(key,val);
        }
        
        if(node->val==val)node->key=key;
        if(node->val<val)node->left=insert(node->left,key,val,k,t);
        if(node->val>val)node->right=insert(node->right,key,val,k,t);
        return node;
    }
    Node* delete_Node(Node* node,long key,long val)
    {
        if(!node)return node;
        if(val>node->val)node->right=delete_Node(node->right,key,val);
        if(val<node->val)node->left=delete_Node(node->left,key,val);
        if(node->key==key)
        {
            if(!node->left)return node->right;
            if(!node->right)return node->left;
            Node* temp=node->right;
            while(temp->left)temp=temp->left;
            node->val=temp->val;node->key=temp->key;
            node->right=delete_Node(node->right,node->key,node->val);
        }
        return node;
    }
        struct Node
    {
        long key,val;
        Node* left,*right;
        Node(long k,long v):key(k),val(v),left(NULL),right(NULL){}
    };
    Node* root=NULL;
    bool result=false;
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.