📖 Scenario: Imagine you have a family tree represented as a binary tree. You want to find the closest common ancestor of two family members.
🎯 Goal: Build a Java 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 a helper method to find the LCA
Use recursion 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 file directory structures to find shared ancestors or common points.
💼 Career
Understanding tree traversal and recursive algorithms is important for software engineering roles, especially those involving data structures, databases, and system design.
Progress0 / 4 steps
1
Create the Binary Tree Structure
Create a class called TreeNode with an int val field, and TreeNode left and TreeNode right fields. Then create a binary tree with root node value 3, left child 5, right child 1, left child of 5 as 6, right child of 5 as 2, left child of 1 as 0, and right child of 1 as 8.
DSA Java
Hint
Start by defining the TreeNode class with the value and two child pointers. Then create the root and assign its children as described.
2
Add the LCA Method Signature
Inside the Main class, add a static method called lowestCommonAncestor that takes three parameters: TreeNode root, TreeNode p, and TreeNode q. The method should return a TreeNode.
DSA Java
Hint
Define the method with the exact name and parameters as described. Return type should be TreeNode.
3
Implement the LCA Recursive Logic
Complete the lowestCommonAncestor method using recursion: if root is null or equals p or q, return root. Recursively call the method on root.left and root.right. If both calls return non-null, return root. Otherwise, return the non-null result.
DSA Java
Hint
Use the recursive approach: check base cases, recurse left and right, then decide which node to return.
4
Print the Lowest Common Ancestor Value
In the main method, call lowestCommonAncestor with root, root.left (node 5), and root.right (node 1). Print the val of the returned node using System.out.println.
DSA Java
Hint
Call the method with the root and the two nodes (5 and 1). Print the val of the returned node.
Practice
(1/5)
1. What is the Lowest Common Ancestor (LCA) of two nodes in a binary tree?
easy
A. The node that is a child of both nodes
B. The deepest node that is an ancestor of both nodes
C. The node with the smallest value between the two nodes
D. The root node of the binary tree
Solution
Step 1: Understand the definition of LCA
The Lowest Common Ancestor is the deepest node in the tree that has both given nodes as descendants (a node can be a descendant of itself).
Step 2: Clarify the options
The deepest node that is an ancestor of both nodes correctly describes the LCA. The root node is not always the LCA, and the smallest value or child relationships do not define LCA.
Final Answer:
The deepest node that is an ancestor of both nodes -> Option B
Quick Check:
LCA = deepest common ancestor [OK]
Hint: LCA is the deepest shared ancestor node [OK]
Common Mistakes:
Confusing LCA with root node
Thinking LCA is the smaller value node
Assuming LCA is a child of given nodes
2. Which of the following is the correct Java method signature to find the LCA of two nodes in a binary tree?
easy
A. public void findLCA(TreeNode root, int n1, int n2)
B. public int findLCA(int root, TreeNode n1, TreeNode n2)
C. public TreeNode findLCA(int n1, int n2)
D. public TreeNode findLCA(TreeNode root, int n1, int n2)
Solution
Step 1: Analyze method parameters and return type
The method should take the root node and two node values (or nodes) to find their LCA. It returns the TreeNode representing the LCA.
Step 2: Match with options
public TreeNode findLCA(TreeNode root, int n1, int n2) matches this: it takes root and two integers, returns TreeNode. public int findLCA(int root, TreeNode n1, TreeNode n2) has wrong parameter types, C misses root, D returns void which is incorrect.
Final Answer:
public TreeNode findLCA(TreeNode root, int n1, int n2) -> Option D
Quick Check:
Correct signature includes root and returns TreeNode [OK]
Hint: LCA method needs root and two nodes, returns TreeNode [OK]
Common Mistakes:
Omitting root parameter
Wrong return type (void or int)
Incorrect parameter order or types
3. Given the following binary tree and code snippet, what will be the output?
Hint: Check both nodes exist before returning LCA [OK]
Common Mistakes:
Ignoring missing node cases
Assuming both nodes always exist
Not validating subtree results properly
5. You have a binary tree where nodes can have duplicate values. How would you modify the standard LCA algorithm to correctly find the LCA of two nodes given their references (not values)?
hard
A. Use node references directly instead of comparing values during recursion
B. Use a hash map to store node values and find LCA by values
C. Ignore duplicates and return the first matching value node as LCA
D. Modify the tree to remove duplicates before finding LCA
Solution
Step 1: Understand the problem with duplicates
When values are duplicated, comparing node values is unreliable to identify nodes uniquely.
Step 2: Use node references for comparison
Instead of comparing values, compare the actual node references (memory addresses) to find exact nodes during recursion.
Step 3: Adjust algorithm accordingly
Modify the LCA method to check if current node == target node references, not values.
Final Answer:
Use node references directly instead of comparing values during recursion -> Option A
Quick Check:
Use references, not values, for duplicates [OK]
Hint: Compare node references, not values, when duplicates exist [OK]
Common Mistakes:
Comparing values instead of references
Trying to remove duplicates unnecessarily
Using value-based hash maps causing errors
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.