Tutorialspoint
Problem
Solution
Submissions

Lowest Common Ancestor

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to find the lowest common ancestor (LCA) of two given nodes in a binary tree. The lowest common ancestor is defined as the lowest node in the tree that has both nodes as descendants (where a node can be a descendant of itself).

Example 1
  • Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
  • Output: 3
  • Explanation:
    • The LCA of nodes 5 and 1 is 3.
Example 2
  • Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
  • Output: 5
  • Explanation:
    • The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
Constraints
  • The number of nodes in the tree is in the range [2, 10^5]
  • -10^9 <= Node.val <= 10^9
  • All Node.val are unique
  • p != q
  • p and q will exist in the tree
  • Time Complexity: O(n), where n is the number of nodes in the tree
  • Space Complexity: O(h), where h is the height of the tree
Binary TreeFacebookGoldman Sachs
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use recursive tree traversal
  • Check if the current node is either p or q
  • Recursively search for p and q in the left and right subtrees
  • If both subtrees return non-null results, the current node is the LCA
  • If one subtree returns a non-null result, that result is the LCA

Steps to solve by this approach:

 Step 1: Define a recursive function that takes the root and the two nodes p and q.
 Step 2: Handle base cases - if the current node is null or equals either p or q, return it.
 Step 3: Recursively search for p and q in the left subtree.
 Step 4: Recursively search for p and q in the right subtree.
 Step 5: If both left and right recursion return non-null values, the current root is the LCA.
 Step 6: If only one recursive call returns non-null, that result is the LCA.
 Step 7: If both return null, return null (neither p nor q found in this subtree).

Submitted Code :