
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
Editorial
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. |
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