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 42275af commit a8fda8fCopy full SHA for a8fda8f
lowest-common-ancestor-of-a-binary-search-tree/njngwn.java
@@ -0,0 +1,23 @@
1
+/**
2
+ * Definition for a binary tree node.
3
+ * public class TreeNode {
4
+ * int val;
5
+ * TreeNode left;
6
+ * TreeNode right;
7
+ * TreeNode(int x) { val = x; }
8
+ * }
9
+ */
10
+
11
+class Solution {
12
+ public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
13
+ if (root.val == p.val || root.val == q.val) return root;
14
15
+ if (p.val < root.val && q.val < root.val) {
16
+ return lowestCommonAncestor(root.left, p, q);
17
+ } else if (p.val > root.val && q.val > root.val) {
18
+ return lowestCommonAncestor(root.right, p, q);
19
+ } else {
20
+ return root;
21
+ }
22
23
+}
0 commit comments