lowest-common-ancestor-of-a-binary-search-tree
This commit is contained in:
parent
afabed5d35
commit
d1d60eb34e
|
@ -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
|
||||
}
|
Loading…
Reference in New Issue