Hi everyone: I read the algorithm below to find the least common ancestor of two nodes in a binary search tree.
struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int );
int leastCommanAncestor(struct node* root, int n1, int n2)
{
if(root == NULL || root->data == n1 || root->data == n2)
return -1;
if((root->right != NULL) &&
(root->right->data == n1 || root->right->data == n2))
return root->data;
if((root->left != NULL) &&
(root->left->data == n1 || root->left->data == n2))
return root->data;
if(root->data > n1 && root->data < n2)
return root->data;
if(root->data > n1 && root->data > n2)
return leastCommanAncestor(root->left, n1, n2);
if(root->data < n1 && root->data < n2)
return leastCommanAncestor(root->right, n1, n2);
}
Note that the above function assumes that n1 is less than n2. Difficulty of time: O (n) Difficulty of space: O (1)
this algorithm is recursive, I know that when calling a call to a recursive function, the function arguments and other related registers are pushed onto the stack, so additional space is required, on the other hand, the recursive depth is related to the size or height of the tree, say n, does it make sense to be O ( n)?
Thanks for any explanation here!
Tracy source
share