mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-24 10:37:33 +08:00
33 lines
586 B
Go
33 lines
586 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 lowestCommonAncestor236(root, p, q *TreeNode) *TreeNode {
|
|
if root == nil || root == q || root == p {
|
|
return root
|
|
}
|
|
left := lowestCommonAncestor236(root.Left, p, q)
|
|
right := lowestCommonAncestor236(root.Right, p, q)
|
|
if left != nil {
|
|
if right != nil {
|
|
return root
|
|
}
|
|
return left
|
|
}
|
|
return right
|
|
}
|