Skip to content

Commit

Permalink
Merge pull request neetcode-gh#983 from t3chkid/main
Browse files Browse the repository at this point in the history
Replace recursive implementation with iterative implantation for 235. Lowest Common Ancestor of a Binary Search Tree in Kotlin
  • Loading branch information
Ahmad-A0 authored Sep 1, 2022
2 parents b201d70 + d1e44a0 commit ea3fa54
Showing 1 changed file with 17 additions and 16 deletions.
33 changes: 17 additions & 16 deletions kotlin/235-Lowest-Common-Ancestor-Of-Binary-Search-Tree.kt
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
/**
* Definition for a binary tree node.
* class TreeNode(var `val`: Int = 0) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class TreeNode(var `val`: Int = 0) {
var left: TreeNode? = null
var right: TreeNode? = null
}

class Solution {
fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? {
if (p!!.`val` > root!!.`val` && q!!.`val` > root!!.`val`) {
return lowestCommonAncestor(root.right, p, q)
fun lowestCommonAncestor(root: TreeNode, p: TreeNode?, q: TreeNode?): TreeNode? {
var currentRoot: TreeNode? = root
var lowestCommonAncestor: TreeNode? = null
while (currentRoot != null) {
if (currentRoot.`val` > p!!.`val` && currentRoot.`val` > q!!.`val`) {
currentRoot = currentRoot.left
} else if (currentRoot.`val` < p.`val` && currentRoot.`val` < q!!.`val`) {
currentRoot = currentRoot.right
} else {
lowestCommonAncestor = currentRoot
break
}
}

if (p!!.`val` < root!!.`val` && q!!.`val` < root!!.`val`) {
return lowestCommonAncestor(root.left, p, q)
}

return root
return lowestCommonAncestor
}
}

0 comments on commit ea3fa54

Please sign in to comment.