First time here? Checkout the FAQ!
+1 vote
can anyone define the procedure to find the common ancestor of any two given nodes in balanced BST..??
asked in DS by Veteran (14.8k points) 15 151 316 | 101 views

2 Answers

+1 vote
Best answer
#define BIGGER 1
#define SMALLER -1
#define EQUAL 0

int compare(int x,int y) {
    if(x == y) return EQUAL;
    else if(x < y) return SMALLER;
    els return BIGGER;

struct node* find_LCA(struct node *root,int a,int b) {
    // I have assumed that a and b exist in the tree already
    if(root != NULL) {
        // compare this node with a
        int res1 = compare(a,root->data); 
        // compare this node with b
        int res2 = compare(b,root->data); 	
    // is any one of a,b is equal to this node value
    // then return this node 
    if(res1 == EQUAL || res2 == EQUAL) {  	
        return root;					
    //  a and b are on different subtree
    else if(res1 != res2) {				
        return root;					  
    else {
    // one of the following recursive call will execute
        if(res1 == BIGGER) {				// or res2 == BIGGER same thing
            return find_LCA(root->right_child,a,b);
        }else {
            return find_LCA(root->left_child,a,b);

  • Best case $O(1)$
  • Worst case $O(\log n)$
  • Checking of null pointers before a recursive call and a=b  or any other code handling issue have has been eliminated for simplicity. 
answered by Veteran (56.9k points) 36 189 500
edited by
For normal binary tree or any rooted tree, and with multiple queries (a,b), this LCA problem is of great interest and very interesting.
+1 vote
will it be like -

first comapring A nd B with the root node..if A< root and B > root then root is the common ancestor..

if A< ROOT & B is also < root then again calling same function with root-> left

if A>root and B is also > root then again calling same function with root -> right

its T(n) will be O(log n)..right?

please verify this
answered by Veteran (14.8k points) 15 151 316

Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
Top Users Oct 2017
  1. Arjun

    23398 Points

  2. Bikram

    17078 Points

  3. Habibkhan

    8264 Points

  4. srestha

    6296 Points

  5. Debashish Deka

    5438 Points

  6. jothee

    4978 Points

  7. Sachin Mittal 1

    4772 Points

  8. joshi_nitish

    4348 Points

  9. sushmita

    3964 Points

  10. Rishi yadav

    3804 Points

Recent Badges

Notable Question Vineeta
Popular Question rahul sharma 5
Famous Question rahuldb
Great Question jothee
Notable Question Vaishali Trivedi
Notable Question KISHALAY DAS
Notable Question sh!va
Notable Question abhijeetbzu
Great Question jothee
Popular Question rahul sharma 5
27,324 questions
35,176 answers
33,279 users