leet-code/lowest-common-ancestor-of-a.../sol.go

31 lines
492 B
Go

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
}