LeetCode 236. 二叉树的最近公共祖先Golang版
1. 问题描述
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
2. 思路
- 确定递归函数参数和返回值
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode
- 确定终止条件
if root == p || root == q || root == nil {
return root
}
- 确定单层递归逻辑
left := lowestCommonAncestor(root.Left, p, q)
right := lowestCommonAncestor(root.Right, p, q)
if left != nil && right != nil {
return root
}
if left == nil && right != nil {
return right
}
if left != nil && right == nil {
return left
}
return nil
3. 代码
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == p || root == q || root == nil {
return root
}
left := lowestCommonAncestor(root.Left, p, q)
right := lowestCommonAncestor(root.Right, p, q)
if left != nil && right != nil {
return root
}
if left == nil && right != nil {
return right
}
if left != nil && right == nil {
return left
}
return nil
}