File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed
lowest-common-ancestor-of-a-binary-search-tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 1+ class TreeNode (var `val `: Int = 0 ) {
2+ var left: TreeNode ? = null
3+ var right: TreeNode ? = null
4+ }
5+
6+
7+ class Solution {
8+
9+ // TC: O(H) - H: height of BST
10+ // SC: O(1) - while loop: X stack
11+ fun lowestCommonAncestor (root : TreeNode ? , p : TreeNode ? , q : TreeNode ? ): TreeNode ? {
12+
13+ if (root == null || p == null || q == null ) return null
14+
15+ // BST: left < parent < right
16+ var current = root
17+ while (current != null ){
18+ if (current.`val ` < p.`val ` && current.`val ` < q.`val `){
19+ current = current.right
20+ }
21+ else if (current.`val ` > p.`val ` && current.`val ` > q.`val `){
22+ current = current.left
23+ }
24+ else return current
25+ }
26+
27+ return null
28+ }
29+
30+ }
You can’t perform that action at this time.
0 commit comments