Skip to content

Latest commit

 

History

History
33 lines (22 loc) · 758 Bytes

Kth common ancestor in BST.md

File metadata and controls

33 lines (22 loc) · 758 Bytes
int kthCommonAncestor(Node *root, int k,int x, int y)
    {
        // your code goes here
        
        vector<int> vec;
        
        while(true)
        {
            vec.push_back(root->data);
            
            if(x > root->data && y>root->data)
                root = root->right;
                
            else if(x< root->data && y< root->data)
                root = root->left;
                
            else
                break;
        }
        
        int t = vec.size()-k;
        
        if(t<vec.size())
            return vec[t];
            
        return -1;
    }