Assignment No 6
Assignment No 6
Assignment No 6
Assignment No-06
Title:
Write a non-recursive version of finding the Least Common Ancestor (LCA) of any two
nodes in a Binary Search Tree (BST) and optimize your non-recursive search by balancing
the tree.
Theory:
A Binary Search Tree is a hierarchical data structure in which each node has at most two
children, referred to as the left child and the right child. BSTs are structured to maintain a
specific ordering property: for any given node, all elements in the left subtree are smaller than
the node, and all elements in the right subtree are larger.
The Least Common Ancestor of two nodes in a BST is defined as the deepest node that is an
ancestor of both nodes. In other words, it's the lowest node in the tree that has both nodes as
descendants.
To find the Least Common Ancestor of two nodes in a BST, we can take advantage of the
ordering property of BSTs. The steps are as follows:
Non-Recursive Algorithm:
struct Node {
int value;
Node* left;
Node* right;};
while (root) {
} else {
To optimize the search, we need to ensure that the tree remains balanced. A balanced BST
ensures that the depth of the tree is logarithmic, keeping the search time efficient.
One popular approach for keeping the tree balanced is to use self-balancing trees such as:
AVL Tree: Rotates nodes to ensure the height difference between subtrees is at most 1.
Red-Black Tree: Ensures that no path is more than twice as long as any other, keeping
operations close to O(logn).
Examples :
Output: 12
Explanation: 12 is the closest node to both 10 and 14
which is a ancestor of both the nodes.
Conclusion:
VPKBIET, Baramati