diff --git a/lowest-common-ancestor-of-a-binary-search-tree/sol.go b/lowest-common-ancestor-of-a-binary-search-tree/sol.go new file mode 100644 index 0000000..c00f683 --- /dev/null +++ b/lowest-common-ancestor-of-a-binary-search-tree/sol.go @@ -0,0 +1,30 @@ +package main + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { + min, max := p, q + if p.Val > q.Val { + min, max = q, p + } + for root.Val < min.Val || root.Val > max.Val { + if root.Val < min.Val { + root = root.Right + } else { + root = root.Left + } + } + return root +}