File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
3+ * time complexity : O(log n)
4+ * space complexity : O(1)
5+ */
6+
7+ class TreeNode {
8+ val : number
9+ left : TreeNode | null
10+ right : TreeNode | null
11+ constructor ( val ?: number , left ?: TreeNode | null , right ?: TreeNode | null ) {
12+ this . val = ( val === undefined ? 0 : val )
13+ this . left = ( left === undefined ? null : left )
14+ this . right = ( right === undefined ? null : right )
15+ }
16+ }
17+
18+ function lowestCommonAncestor ( root : TreeNode | null , p : TreeNode , q : TreeNode ) : TreeNode | null {
19+ while ( root ) {
20+ if ( p . val < root . val && q . val < root . val ) root = root . left ;
21+ else if ( p . val > root . val && q . val > root . val ) root = root . right ;
22+ else return root ;
23+ }
24+ return null ;
25+ } ;
You can’t perform that action at this time.
0 commit comments