← 返回 meta 的题目列表Lowest Common Ancestor in a Binary Tree
类型:online_judge
Given a binary tree and two nodes p and q in the tree, find and return their lowest common ancestor (LCA). Each node has a unique value. The tree is not necessarily complete. Implement your solution with O(n) time complexity.
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 its own LCA.
Constraints: Total number of nodes in the tree is less than 10^4; the tree is a binary tree.
Example
Input
3
5
1
6
2
0
8
null
null
7
4
5
1