LCA in BST
#include<iostream>
#include <algorithm>
using namespace std;
/************************************************************************/
/* tail recursive: complexity: O(h), h is the height of BST
Node *LCA(Node *root, Node *p, Node *q) {
if (!root || !p || !q) return NULL;
if (max(p->data, q->data) < root->data)
return LCA(root->left, p, q);
else if (min(p->data, q->data) > root->data)
return LCA(root->right, p, q);
else
return root;
}
*/
/* iterative way.. start from the root, and top-down
*/
/************************************************************************/
struct node
{
int val;
node *left;
node *right;
};
node * BST_LCA(node *root, node *n1, node *n2) {
while (root != NULL)
{
if ( max(n1->val, n2->val) < root->val ) // left of subtree
root = root->left;
else if (min(n1->val, n2->val) > root->val)
root = root->right;
else return root;
}
}
Comments
Post a Comment