0
0
DSA Goprogramming~30 mins

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

Choose your learning style9 modes available
Lowest Common Ancestor in Binary Tree
📖 Scenario: You are working on a family tree application. You want to find the closest common ancestor of two family members in the tree.
🎯 Goal: Build a program that finds the Lowest Common Ancestor (LCA) of two nodes in a binary tree.
📋 What You'll Learn
Create a binary tree with specific nodes
Add variables for the two target nodes
Implement a function to find the LCA
Print the value of the LCA node
💡 Why This Matters
🌍 Real World
Finding the lowest common ancestor is useful in family trees, organizational charts, and network routing to find shared connections.
💼 Career
Understanding tree traversal and recursive algorithms is important for software engineering roles involving data structures, databases, and system design.
Progress0 / 4 steps
1
Create the Binary Tree
Create a binary tree with the following structure using TreeNode structs:

Root node with value 3
Left child with value 5
Right child with value 1
Left child of node 5 with value 6
Right child of node 5 with value 2
Left child of node 1 with value 0
Right child of node 1 with value 8
Left child of node 2 with value 7
Right child of node 2 with value 4
Assign the root node to a variable called root.
DSA Go
Hint

Start by creating the root node with value 3. Then create child nodes and assign them to the Left and Right fields accordingly.

2
Set Target Nodes for LCA
Create two variables called p and q that point to the nodes with values 5 and 1 respectively in the tree.
DSA Go
Hint

Assign p to the left child of root and q to the right child of root.

3
Implement the Lowest Common Ancestor Function
Write a function called lowestCommonAncestor that takes root, p, and q as parameters (all of type *TreeNode) and returns the lowest common ancestor node. Use recursion to find the LCA.
DSA Go
Hint

Use recursion to search left and right subtrees. If both sides return non-nil, current node is LCA. If one side returns non-nil, return that side.

4
Print the Lowest Common Ancestor Value
Call the lowestCommonAncestor function with root, p, and q. Print the Val field of the returned node using fmt.Println.
DSA Go
Hint

Call lowestCommonAncestor(root, p, q) and store the result in a variable. Then print the Val of that variable.