File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ class TreeNode {
2
+ val : number ;
3
+ left : TreeNode | null ;
4
+ right : TreeNode | null ;
5
+ constructor ( val ?: number , left ?: TreeNode | null , right ?: TreeNode | null ) {
6
+ this . val = val === undefined ? 0 : val ;
7
+ this . left = left === undefined ? null : left ;
8
+ this . right = right === undefined ? null : right ;
9
+ }
10
+ }
11
+
12
+ // TC: O(n)
13
+ // SC: O(1)
14
+ function lowestCommonAncestor (
15
+ root : TreeNode | null ,
16
+ p : TreeNode | null ,
17
+ q : TreeNode | null
18
+ ) : TreeNode | null {
19
+ if ( ! root || ! p || ! q ) return null ;
20
+
21
+ let node = root ;
22
+
23
+ while ( node ) {
24
+ if ( node . val < p . val && node . val < q . val ) {
25
+ node = node . right ! ;
26
+ } else if ( node . val > p . val && node . val > q . val ) {
27
+ node = node . left ! ;
28
+ } else {
29
+ return node ;
30
+ }
31
+ }
32
+
33
+ return null ;
34
+ }
35
+
36
+
37
+ // TC: O(n)
38
+ // SC: O(n)
39
+ // function lowestCommonAncestor(
40
+ // root: TreeNode | null,
41
+ // p: TreeNode | null,
42
+ // q: TreeNode | null
43
+ // ): TreeNode | null {
44
+ // if (!root || !p || !q) return null;
45
+
46
+ // if (p.val < root.val && q.val < root.val) {
47
+ // return lowestCommonAncestor(root.left, p, q);
48
+ // } else if (p.val > root.val && q.val > root.val) {
49
+ // return lowestCommonAncestor(root.right, p, q);
50
+ // } else {
51
+ // return root;
52
+ // }
53
+ // }
You can’t perform that action at this time.
0 commit comments