We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent d57d334 commit 43c4a66Copy full SHA for 43c4a66
lowest-common-ancestor-of-a-binary-search-tree/forest000014.java
@@ -0,0 +1,28 @@
1
+/*
2
+# Time Complexity: O(n)
3
+# Space Compleixty: O(1)
4
+*/
5
+
6
+/**
7
+ * Definition for a binary tree node.
8
+ * public class TreeNode {
9
+ * int val;
10
+ * TreeNode left;
11
+ * TreeNode right;
12
+ * TreeNode(int x) { val = x; }
13
+ * }
14
+ */
15
16
+class Solution {
17
+ public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
18
+ // null check unnecessary
19
20
+ if (root.val > p.val && root.val > q.val) {
21
+ return lowestCommonAncestor(root.left, p, q);
22
+ } else if (root.val < p.val && root.val < q.val) {
23
+ return lowestCommonAncestor(root.right, p, q);
24
+ } else {
25
+ return root;
26
+ }
27
28
+}
0 commit comments