You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
3
+
4
+
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
5
+
6
+
Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5]
7
+
8
+
_______6______
9
+
/ \
10
+
___2__ ___8__
11
+
/ \ / \
12
+
0 _4 7 9
13
+
/ \
14
+
3 5
15
+
Example 1:
16
+
17
+
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
18
+
Output: 6
19
+
Explanation: The LCA of nodes 2 and 8 is 6.
20
+
Example 2:
21
+
22
+
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
23
+
Output: 2
24
+
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself
25
+
according to the LCA definition.
26
+
Note:
27
+
28
+
All of the nodes' values will be unique.
29
+
p and q are different and both values will exist in the BST.
0 commit comments