Lowest common ancestor in a BST
suggest changeConsider the BST:
The lowest common ancestor of 22 and 26 is 24.
The lowest common ancestor of 26 and 49 is 46.
The lowest common ancestor of 22 and 24 is 24.
The binary-search-tree ordering property can be used to find the lowest common ancestor.
Pseudocode:
lowestCommonAncestor(root,node1, node2){
if(root == NULL)
return NULL;
else if(node1->data == root->data || node2->data== root->data)
return root;
else if((node1->data <= root->data && node2->data > root->data)
|| (node2->data <= root->data && node1->data > root->data)) {
return root;
}
else if(root->data > max(node1->data,node2->data)){
return lowestCommonAncestor(root->left, node1, node2);
}
else {
return lowestCommonAncestor(root->right, node1, node2);
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents