From 9fa6578ce7da9b123ed235f30a07577b1f72151e Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Fri, 12 Aug 2022 22:10:33 +0200 Subject: [PATCH] =?UTF-8?q?problems:=20add=20=E2=80=9E235.=20Lowest=20Comm?= =?UTF-8?q?on=20Ancestor=20of=20a=20Binary=20Search=20Tree=E2=80=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- ...common-ancestor-of-a-binary-search-tree.kt | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 problems/lowest-common-ancestor-of-a-binary-search-tree.kt diff --git a/problems/lowest-common-ancestor-of-a-binary-search-tree.kt b/problems/lowest-common-ancestor-of-a-binary-search-tree.kt new file mode 100644 index 0000000..b999733 --- /dev/null +++ b/problems/lowest-common-ancestor-of-a-binary-search-tree.kt @@ -0,0 +1,37 @@ +/** + * Definition for a binary tree node. + * 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? { + var ancestor: TreeNode? = null + var pTrack = root + var qTrack = root + + while (pTrack == qTrack && pTrack != null && qTrack != null) { + ancestor = pTrack + + if (pTrack!!.`val` == p!!.`val`) { + return p + } else if (p!!.`val` < pTrack!!.`val`) { + pTrack = pTrack.left + } else { + pTrack = pTrack.right + } + + if (qTrack!!.`val` == q!!.`val`) { + return q + } else if (q!!.`val` < qTrack!!.`val`) { + qTrack = qTrack.left + } else { + qTrack = qTrack.right + } + } + + return ancestor + } +}