0
0
DSA Javascriptprogramming~30 mins

Lowest Common Ancestor in Binary Tree in DSA Javascript - Build from Scratch

Choose your learning style9 modes available
Lowest Common Ancestor in Binary Tree
📖 Scenario: Imagine a family tree where each person has two parents at most. We want to find the closest common ancestor of two family members.
🎯 Goal: Build a simple binary tree and write a function to find the lowest common ancestor (LCA) of two given nodes.
📋 What You'll Learn
Create a binary tree with specific nodes
Add a helper function to find nodes by value
Write a function to find the lowest common ancestor of two nodes
Print the value of the lowest common ancestor
💡 Why This Matters
🌍 Real World
Finding common ancestors is useful in family trees, organizational charts, and file systems to understand relationships.
💼 Career
Understanding tree traversal and ancestor queries is important for software engineers working with hierarchical data and algorithms.
Progress0 / 4 steps
1
Create the Binary Tree Nodes
Create a binary tree by defining a class called TreeNode with a constructor that takes val, left, and right. Then create nodes with values 3, 5, 1, 6, 2, 7, 4, 0, and 8 and link them to form this tree:

3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
DSA Javascript
Hint

Start by defining the TreeNode class. Then create each node from bottom to top, linking children to parents.

2
Add a Function to Find a Node by Value
Add a function called findNode that takes root and val and returns the node with that value by searching the tree recursively.
DSA Javascript
Hint

Use recursion to check if the current node matches val. If not, search left and right subtrees.

3
Write the Lowest Common Ancestor Function
Write a function called lowestCommonAncestor that takes root, p, and q (nodes) and returns their lowest common ancestor node using recursion.
DSA Javascript
Hint

Use recursion to check left and right subtrees. If both sides return a node, current root is LCA. Otherwise, return the non-null side.

4
Find and Print the Lowest Common Ancestor
Use findNode to get nodes p with value 5 and q with value 1. Then call lowestCommonAncestor(root, p, q) and print the val of the result.
DSA Javascript
Hint

Use findNode to get nodes for 5 and 1. Then call lowestCommonAncestor with these nodes and print the val of the result.