Lowest Common Ancestor in BST
Lowest Common Ancestor is parent of both node or node itself.
we have following cases:
1: either node is equal to one of argument
Then it will be LCA
2 : if one node lies in left one in and right child
Then it will be LCA
Code:
Node LCA(Node node,int min,int max)
{
if(node==null)
return null;
if((node.data>=min && node.data<=max))
return node;
if(node.data<min && node.data<max)
return LCA(node.right,min,max);
return LCA(node.left,min,max);
}
Node lca(Node node, int n1, int n2)
{
int min=Math.min(n1,n2);
int max=Math.max(n2,n1);
return LCA(node,min,max);
}
we have following cases:
1: either node is equal to one of argument
Then it will be LCA
2 : if one node lies in left one in and right child
Then it will be LCA
Code:
Node LCA(Node node,int min,int max)
{
if(node==null)
return null;
if((node.data>=min && node.data<=max))
return node;
if(node.data<min && node.data<max)
return LCA(node.right,min,max);
return LCA(node.left,min,max);
}
Node lca(Node node, int n1, int n2)
{
int min=Math.min(n1,n2);
int max=Math.max(n2,n1);
return LCA(node,min,max);
}
0 Comments:
Post a Comment