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
Copy file name to clipboardexpand all lines: solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/README_EN.md
+74-6
Original file line number
Diff line number
Diff line change
@@ -64,7 +64,11 @@ tags:
64
64
65
65
<!-- solution:start -->
66
66
67
-
### Solution 1
67
+
### Solution 1: Iteration
68
+
69
+
Starting from the root node, we traverse the tree. If the current node's value is less than both $\textit{p}$ and $\textit{q}$ values, it means that $\textit{p}$ and $\textit{q}$ should be in the right subtree of the current node, so we move to the right child. If the current node's value is greater than both $\textit{p}$ and $\textit{q}$ values, it means that $\textit{p}$ and $\textit{q}$ should be in the left subtree, so we move to the left child. Otherwise, it means the current node is the lowest common ancestor of $\textit{p}$ and $\textit{q}$, so we return the current node.
70
+
71
+
The time complexity is $O(n)$, where $n$ is the number of nodes in the binary search tree. The space complexity is $O(1)$.
We can also use a recursive approach to solve this problem.
252
+
253
+
We first check if the current node's value is less than both $\textit{p}$ and $\textit{q}$ values. If it is, we recursively traverse the right subtree. If the current node's value is greater than both $\textit{p}$ and $\textit{q}$ values, we recursively traverse the left subtree. Otherwise, it means the current node is the lowest common ancestor of $\textit{p}$ and $\textit{q}$, so we return the current node.
254
+
255
+
The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary search tree.
218
256
219
257
<!-- tabs:start -->
220
258
@@ -338,12 +376,42 @@ function lowestCommonAncestor(
338
376
p:TreeNode|null,
339
377
q:TreeNode|null,
340
378
):TreeNode|null {
341
-
if (root.val>p.val&&root.val>q.val) returnlowestCommonAncestor(root.left, p, q);
342
-
if (root.val<p.val&&root.val<q.val) returnlowestCommonAncestor(root.right, p, q);
0 commit comments