LCA in Binary Tree using JavaScript
Last Updated :
10 Apr, 2024
The lowest common ancestor between two nodes n1 and n2 in a binary tree is defined as the lowest node in a Tree that has both n1 and n2 as descendants. If either n1 or n2 is not present in the tree, or if they are not connected through a common ancestor, the LCA of the binary tree is NULL. Below is an example to understand the LCA of the binary tree clearly.
Lowest Common Ancestor for node 6 & 7 is 3 in the above Binary search treeThere are several approaches available in JavaScript to find Lowest Common Ancestor in Binary Tree which are as follows:
Recursive Approach
The Function first checks if the root is null or either of the given nodes is the root. If so, it returns the root. Then, it recursively explores the left and right subtrees. If both subtrees return non-null values, indicating that the nodes are found in different subtrees, the current root is the LCA. Otherwise, it returns the non-null value from either subtree. If both subtrees return null, the function returns null.
Example : To demonstrate finding Lowest Common Ancestor in Binary Tree using Recursive Approach
JavaScript
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
function lowestCommonAncestor(root, p, q) {
if (root === null) {
return null;
}
if (root === p || root === q) {
return root;
}
const left =
lowestCommonAncestor(root.left, p, q);
const right =
lowestCommonAncestor(root.right, p, q);
if (left !== null && right !== null) {
return root;
}
return left !== null ? left : right;
}
const root = new TreeNode(3);
root.left = new TreeNode(5);
root.right = new TreeNode(1);
root.left.left = new TreeNode(6);
root.left.right = new TreeNode(2);
root.left.right.left = new TreeNode(7);
root.left.right.right = new TreeNode(4);
root.right.left = new TreeNode(0);
root.right.right = new TreeNode(8);
const p = root.right;
const q = root.left;
console.log("LCA of Binary tree using recursive approach is :",
lowestCommonAncestor(root, p, q));
OutputLCA of Binary tree using recursive approach is : 3
Time complexity: O(n) , n is number of nodes in BT
Space complexity: O(h) , h is height of BT.
Parent Pointer Approach
Define a function which traverses the binary tree and constructs parent pointers for each node. Traverse from one given node to the root while storing each ancestor in a map. now Traverse from another node to the root and at each step check if the current ancestor of q exists in the parentMap. If found, return the current ancestor as the Lowest Common Ancestor else return null.
Example : To demonstrate finding Lowest Common Ancestor in Binary Tree using Parent Pointer Approach
JavaScript
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
this.parent = null;
}
}
function ParentPointers(root, parent = null) {
if (root === null) {
return;
}
root.parent = parent;
ParentPointers(root.left, root);
ParentPointers(root.right, root);
}
function lowestCommonAncestor(root, p, q) {
const parentMap = new Map();
// Construct parent pointers
ParentPointers(root);
// Traverse from p to root
// & store the ancestors in map
while (p !== null) {
parentMap.set(p, true);
p = p.parent;
}
while (q !== null) {
if (parentMap.has(q)) {
// return LCA
return q.value;
}
q = q.parent;
}
return null;
}
const root = new TreeNode(3);
root.left = new TreeNode(5);
root.right = new TreeNode(1);
root.left.left = new TreeNode(6);
root.left.right = new TreeNode(2);
root.left.right.left = new TreeNode(7);
root.left.right.right = new TreeNode(4);
root.right.left = new TreeNode(0);
root.right.right = new TreeNode(8);
const p = root.right.left;
const q = root.left.right;
console.log(" Lowest Common Ancestor in Binary Tree using Parent Pointer Approach is : ",
lowestCommonAncestor(root, p, q));
Output Lowest Common Ancestor in Binary Tree using Parent Pointer Approach is : 3
Time complexity: O(n + h) , n is number of nodes and h is height of binary tree
Space complexity: O(h)
Similar Reads
Height of Binary Tree using JavaScript The height of a binary tree can be defined as the maximum depth or length of the longest path from the root node to any leaf node. Below is an example to illustrate the height of the binary tree. Height of Binary tree is 3There are several approaches to find height of Binary tree using JavaScript wh
3 min read
Kth Ancestor in Binary Tree using JavaScript Given a binary tree and a node in this tree, our task is to find the k-th ancestor of the specified node in JavaScript. If no such ancestor exists, or when k exceeds the depth of the node, the function should return null. Example: Input: Node = 5, k = 2Output: 1ApproachFirst, calculate the depth of
2 min read
Insert a Node in Binary tree using JavaScript A binary tree is a tree data structure where each node has at most two children, referred to as the left child and the right child. The topmost node is called the root. Nodes can have values or data, and the left child's value is less than the parent's value, while the right child's value is greater
3 min read
Sum of Left leaves in Binary Tree using JavaScript Calculating the sum of all left leaves in a binary tree is a common task that helps in understanding tree traversal techniques. A left leaf is defined as a leaf node that is the left child of its parent node. This problem can serve various purposes, such as evaluating symmetry in data structures or
5 min read
Find the Mode in a Binary Search Tree using JavaScript One can find the mode in a binary search tree using JavaScript. The mode in the binary search tree will be the value of the node that occurs with the highest frequency among all the nodes in the tree. If there is more than one mode present in the binary search tree then return all modes present in t
3 min read
Kth Largest/Smallest Element in Binary Search Tree using JavaScript A binary search tree is a type of binary tree in which each node has two children: left child & right child. In a Binary search tree (BST) all nodes in the left subtree have values less than the node value and all nodes in the right subtree have values greater than the node value. Different appr
4 min read
Search a Given Key in BST using JavaScript Given a binary search tree and a key, determine if the key is present in the tree. If the key is present, return the node containing the key otherwise, return null. Example: Input : {15,20,10,8,12,16,25}, Key : 20Output : 20 found 15 / \ 10 20 / \ / \ 8 12 16 25Table of Content Recursive ApproachIte
3 min read
Find Distance Between Two Nodes of a Binary Tree using JavaScript In computer science, binary trees are hierarchical data structures that consist of nodes. Each node can have two children at most - one on the leÂft side and one on the right. These structures have a top-to-bottom order. Solving for distance between any two giveÂn nodes is a problem often seÂen w
7 min read
Return the Leftmost Value in the Last Row of the Binary Tree using JavaScript Given the root of a binary tree, our task is to return the leftmost value in the last row of the binary tree in JavaScript. Here we use recursive and iterative approaches to return the leftmost value in the last row. Explanation: The image below illustrates the leftmost value in the last row of the
3 min read
JavaScript Program to Find Sum of Leaf Node in Binary Tree Given a binary tree, We have to find the sum of all leaf nodes. A leaf node is a node that does not have any children. Example: Input binary tree: 1 / \ 2 3 / \ / \ 4 5 6 7The sum of leaf nodes would be: 4 + 5 + 6 + 7 = 22Table of Content Using recursive approachIterative Approach Using StackUsing r
3 min read