mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-24 19:04:32 +08:00
31 lines
590 B
Go
31 lines
590 B
Go
package leetcode
|
|
|
|
import (
|
|
"github.com/halfrost/LeetCode-Go/structures"
|
|
)
|
|
|
|
// TreeNode define
|
|
type TreeNode = structures.TreeNode
|
|
|
|
/**
|
|
* Definition for a binary tree node.
|
|
* type TreeNode struct {
|
|
* Val int
|
|
* Left *TreeNode
|
|
* Right *TreeNode
|
|
* }
|
|
*/
|
|
|
|
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
|
|
if p == nil || q == nil || root == nil {
|
|
return nil
|
|
}
|
|
if p.Val < root.Val && q.Val < root.Val {
|
|
return lowestCommonAncestor(root.Left, p, q)
|
|
}
|
|
if p.Val > root.Val && q.Val > root.Val {
|
|
return lowestCommonAncestor(root.Right, p, q)
|
|
}
|
|
return root
|
|
}
|