lowest-common-ancestor-of-a-binary-search-tree

This commit is contained in:
Gleb Koval 2022-06-10 13:57:54 +01:00
parent afabed5d35
commit d1d60eb34e
Signed by: cyclane
GPG Key ID: 15E168A8B332382C
1 changed files with 30 additions and 0 deletions

View File

@ -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
}