32 lines
594 B
Go
32 lines
594 B
Go
// Package q236 implements a solution for https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
|
|
package q236
|
|
|
|
type TreeNode struct {
|
|
Val int
|
|
Left *TreeNode
|
|
Right *TreeNode
|
|
}
|
|
|
|
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
|
|
if root == nil {
|
|
return nil
|
|
}
|
|
if root == p || root == q {
|
|
return root
|
|
}
|
|
|
|
l := lowestCommonAncestor(root.Left, p, q)
|
|
r := lowestCommonAncestor(root.Right, p, q)
|
|
|
|
switch {
|
|
case l == nil && r == nil:
|
|
return nil
|
|
case l != nil && r != nil:
|
|
return root
|
|
case l != nil:
|
|
return l
|
|
}
|
|
return r
|
|
}
|
|
|
|
var _ = lowestCommonAncestor
|