Bird
Raised Fist0
DSA Pythonprogramming~30 mins

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

Choose your learning style10 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 to find 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
Write a function to find the LCA of the two nodes
Print the value of the LCA node
💡 Why This Matters
🌍 Real World
Finding common ancestors is useful in family trees, organizational charts, and network routing.
💼 Career
Understanding tree traversal and recursion is important for software engineering roles involving data structures and algorithms.
Progress0 / 4 steps
1
Create the binary tree nodes
Create a class called Node with an __init__ method that takes val, left, and right parameters. Then create the 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. The left and right children of 2 are 7 and 4 respectively.
DSA Python
Hint

Define the Node class first. Then create each node and link them as left or right children.

2
Set the two target nodes
Create two variables called p and q and assign them to the nodes with values 5 and 1 from the tree.
DSA Python
Hint

Use the root's left and right properties to assign p and q.

3
Write the function to find the Lowest Common Ancestor
Write a function called lowestCommonAncestor that takes root, p, and q as parameters. Use recursion to find and return the lowest common ancestor node of p and q in the binary tree.
DSA Python
Hint

Use recursion to check left and right subtrees. Return the root if it matches p or q. If both sides return a node, root is the LCA.

4
Print the value of the Lowest Common Ancestor
Call the lowestCommonAncestor function with root, p, and q and print the val of the returned node.
DSA Python
Hint

Call the function and print the val attribute of the result.

Practice

(1/5)
1. What is the Lowest Common Ancestor (LCA) of two nodes in a binary tree?
easy
A. The root node of the binary tree
B. The node with the smallest value between the two nodes
C. The deepest node that is an ancestor of both nodes
D. The parent node of the first node

Solution

  1. 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.
  2. Step 2: Compare options with definition

    The deepest node that is an ancestor of both nodes matches the definition exactly. Other options describe different nodes.
  3. Final Answer:

    The deepest node that is an ancestor of both nodes -> Option C
  4. Quick Check:

    LCA = deepest common ancestor [OK]
Hint: LCA is the deepest shared parent node [OK]
Common Mistakes:
  • Confusing LCA with root node
  • Thinking LCA is the smaller value node
  • Assuming LCA is always the parent of one node
2. Which of the following is the correct Python function signature to find LCA in a binary tree node class named TreeNode?
easy
A. def find_lca(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
B. def find_lca(root, p, q): return int
C. def find_lca(root: int, p: int, q: int) -> TreeNode:
D. def find_lca(root: TreeNode, p: TreeNode, q: TreeNode): return str

Solution

  1. Step 1: Check parameter types and return type

    The function should accept three TreeNode objects and return a TreeNode object representing the LCA.
  2. Step 2: Match with options

    def find_lca(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode: correctly uses type hints for parameters and return type. Others have wrong types or return types.
  3. Final Answer:

    def find_lca(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode: -> Option A
  4. Quick Check:

    Correct signature uses TreeNode and returns TreeNode [OK]
Hint: Use TreeNode type hints for nodes and return [OK]
Common Mistakes:
  • Using int instead of TreeNode for parameters
  • Returning wrong type like int or str
  • Omitting return type annotation
3. Given the following binary tree and code, what will be the output?
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def lowestCommonAncestor(root, p, q):
    if not root or root == p or root == q:
        return root
    left = lowestCommonAncestor(root.left, p, q)
    right = lowestCommonAncestor(root.right, p, q)
    if left and right:
        return root
    return left if left else right

# Tree:
#       3
#      / \
#     5   1
#    / \ / \
#   6  2 0  8
#     / \
#    7   4

root = TreeNode(3)
root.left = TreeNode(5)
root.right = TreeNode(1)
root.left.left = TreeNode(6)
root.left.right = TreeNode(2)
root.right.left = TreeNode(0)
root.right.right = TreeNode(8)
root.left.right.left = TreeNode(7)
root.left.right.right = TreeNode(4)

p = root.left  # Node 5
q = root.left.right.right  # Node 4

ancestor = lowestCommonAncestor(root, p, q)
print(ancestor.val)
medium
A. 4
B. 3
C. 2
D. 5

Solution

  1. Step 1: Trace recursive calls for nodes 5 and 4

    Node 5 is root.left, node 4 is root.left.right.right. The LCA is the lowest node that has both as descendants. Node 5 is an ancestor of node 4.
  2. Step 2: Identify the LCA node

    Since 5 is ancestor of 4, LCA is node 5 itself.
  3. Final Answer:

    5 -> Option D
  4. Quick Check:

    LCA(5,4) = 5 [OK]
Hint: If one node is ancestor of other, LCA is that node [OK]
Common Mistakes:
  • Choosing root (3) instead of ancestor node
  • Confusing node values with LCA
  • Ignoring that node can be ancestor of itself
4. The following code attempts to find the LCA but has a bug. What is the error?
def lowestCommonAncestor(root, p, q):
    if not root:
        return None
    if root == p or root == q:
        return root
    left = lowestCommonAncestor(root.left, p, q)
    right = lowestCommonAncestor(root.right, p, q)
    if left and right:
        return root
    if left:
        return left
    else:
        return right

# Bug: The function sometimes returns None even if both nodes exist in tree.
medium
A. The function should not return root when left and right are both found
B. The function does not check if both nodes exist in the tree before returning
C. The function should return left and right together instead of root when both exist
D. The base case should return root instead of None when root is None

Solution

  1. Step 1: Analyze base cases and recursive returns

    The function returns None if root is None, and returns root if root matches p or q. It then searches left and right subtrees.
  2. Step 2: Identify missing check for node existence

    If one node is not in the tree, the function may return None incorrectly. It does not verify both nodes exist before returning LCA.
  3. Final Answer:

    The function does not check if both nodes exist in the tree before returning -> Option B
  4. Quick Check:

    Missing node existence check causes None returns [OK]
Hint: Verify both nodes exist before returning LCA [OK]
Common Mistakes:
  • Assuming both nodes always exist in tree
  • Changing base case to return root when root is None
  • Returning root incorrectly when both left and right found
5. You have a binary tree where nodes can have duplicate values. How should you modify the LCA function to correctly find the LCA of two nodes p and q given only their values (not references)?
hard
A. Modify the function to find all nodes with given values and find LCA of all pairs
B. Use node references instead of values to avoid ambiguity
C. Modify the function to search nodes by value and return the first matching node found
D. Return the root node always since duplicates confuse the search

Solution

  1. Step 1: Understand problem with duplicate values

    When values are duplicated, searching by value alone can find multiple nodes, so LCA must consider all matching nodes.
  2. Step 2: Modify approach to handle duplicates

    Find all nodes matching p and q values, then compute LCA for each pair to find the correct lowest common ancestor.
  3. Final Answer:

    Modify the function to find all nodes with given values and find LCA of all pairs -> Option A
  4. Quick Check:

    Handle duplicates by checking all matching nodes [OK]
Hint: Check all nodes with values to handle duplicates [OK]
Common Mistakes:
  • Using only first found node causing wrong LCA
  • Assuming node references are always available
  • Returning root node incorrectly for duplicates
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard