File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +52
-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+ /**
13+ * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description
14+ * T.C. O(log n)
15+ * S.C. O(log n)
16+ */
17+ function lowestCommonAncestor (
18+ root : TreeNode | null ,
19+ p : TreeNode | null ,
20+ q : TreeNode | null
21+ ) : TreeNode | null {
22+ if ( ! root ) return null ;
23+ if ( root . val > p ! . val && root . val > q ! . val ) {
24+ return lowestCommonAncestor ( root . left , p , q ) ;
25+ } else if ( root . val < p ! . val && root . val < q ! . val ) {
26+ return lowestCommonAncestor ( root . right , p , q ) ;
27+ } else {
28+ return root ;
29+ }
30+ }
31+
32+ /**
33+ * iterative
34+ * T.C. O(log n)
35+ * S.C. O(1)
36+ */
37+ function lowestCommonAncestor (
38+ root : TreeNode | null ,
39+ p : TreeNode | null ,
40+ q : TreeNode | null
41+ ) : TreeNode | null {
42+ while ( root ) {
43+ if ( root . val > p ! . val && root . val > q ! . val ) {
44+ root = root . left ;
45+ } else if ( root . val < p ! . val && root . val < q ! . val ) {
46+ root = root . right ;
47+ } else {
48+ return root ;
49+ }
50+ }
51+ return null ;
52+ }
You can’t perform that action at this time.
0 commit comments