Bird
Raised Fist0
DSA Pythonprogramming~20 mins

Lowest Common Ancestor in Binary Tree in DSA Python - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
LCA Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of LCA for given nodes in a binary tree
What is the output of the following code that finds the Lowest Common Ancestor (LCA) of nodes 5 and 1 in the binary tree?
DSA Python
class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

def lca(root, p, q):
    if root is None or root.val == p or root.val == q:
        return root
    left = lca(root.left, p, q)
    right = lca(root.right, p, q)
    if left and right:
        return root
    return left if left else right

# Construct the tree
root = Node(3)
root.left = Node(5)
root.right = Node(1)
root.left.left = Node(6)
root.left.right = Node(2)
root.right.left = Node(0)
root.right.right = Node(8)
root.left.right.left = Node(7)
root.left.right.right = Node(4)

ancestor = lca(root, 5, 1)
print(ancestor.val if ancestor else None)
ANone
B5
C1
D3
Attempts:
2 left
💡 Hint
Think about where the paths to nodes 5 and 1 meet in the tree.
❓ Predict Output
intermediate
2:00remaining
Output of LCA for nodes in same subtree
What is the output of the code that finds the Lowest Common Ancestor (LCA) of nodes 7 and 4 in the binary tree?
DSA Python
class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

def lca(root, p, q):
    if root is None or root.val == p or root.val == q:
        return root
    left = lca(root.left, p, q)
    right = lca(root.right, p, q)
    if left and right:
        return root
    return left if left else right

# Construct the tree
root = Node(3)
root.left = Node(5)
root.right = Node(1)
root.left.left = Node(6)
root.left.right = Node(2)
root.right.left = Node(0)
root.right.right = Node(8)
root.left.right.left = Node(7)
root.left.right.right = Node(4)

ancestor = lca(root, 7, 4)
print(ancestor.val if ancestor else None)
A4
B5
C2
D7
Attempts:
2 left
💡 Hint
Both nodes are in the right subtree of node 5.
🔧 Debug
advanced
2:00remaining
Identify the error in LCA function
What error will the following code raise when trying to find the LCA of nodes 5 and 6?
DSA Python
class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

def lca(root, p, q):
    if root is None:
        return None
    if root.val == p:
        return root
    if root.val == q:
        return root
    left = lca(root.left, p, q)
    right = lca(root.right, p, q)
    if left and right:
        return root
    return left if left else right

root = Node(3)
root.left = Node(5)
root.right = Node(1)
ancestor = lca(root, 5, 6)
print(ancestor.val)
ATypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
BAttributeError: 'int' object has no attribute 'val'
CNone
D3
Attempts:
2 left
💡 Hint
Check what the function returns when root.val matches p or q.
🧠 Conceptual
advanced
1:00remaining
Understanding LCA when one node is ancestor of the other
In a binary tree, if one node is the ancestor of the other, what will the Lowest Common Ancestor (LCA) function return?
AThe ancestor node itself
BThe descendant node
CThe root node of the tree
DNone
Attempts:
2 left
💡 Hint
Think about the definition of ancestor and how the LCA function works.
🚀 Application
expert
3:00remaining
Find LCA in a binary tree with missing nodes
Given the binary tree below, what is the output of finding the LCA of nodes 7 and 10? Tree structure: - 3 - 5 - 6 - 2 - 7 - 4 - 1 - 0 - 8 Note: Node 10 does not exist in the tree.
DSA Python
class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

def lca(root, p, q):
    if root is None or root.val == p or root.val == q:
        return root
    left = lca(root.left, p, q)
    right = lca(root.right, p, q)
    if left and right:
        return root
    return left if left else right

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

ancestor = lca(root, 7, 10)
print(ancestor.val if ancestor else None)
A7
BNone
C2
D3
Attempts:
2 left
💡 Hint
If one node is missing, the function returns the node found if any.

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