File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * function TreeNode(val) {
4
+ * this.val = val;
5
+ * this.left = this.right = null;
6
+ * }
7
+ */
8
+ /**
9
+ * @param {TreeNode } root
10
+ * @param {TreeNode } p
11
+ * @param {TreeNode } q
12
+ * @return {TreeNode }
13
+ */
14
+ var lowestCommonAncestor = function ( root , p , q ) {
15
+ if ( root . val < p . val && root . val < q . val ) {
16
+ return lowestCommonAncestor ( root . right , p , q ) ;
17
+ }
18
+
19
+ if ( root . val > p . val && root . val > q . val ) {
20
+ return lowestCommonAncestor ( root . left , p , q ) ;
21
+ }
22
+
23
+ return root ;
24
+ } ;
25
+
26
+ /**
27
+ * Time Complexity: O(h), where h is the height of the binary search tree.
28
+ * Space Complexity: O(h), where h is the height of the binary search tree.
29
+ */
You can’t perform that action at this time.
0 commit comments