/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == nil {
return nil
}
//
if root.Val == p.Val || root.Val == q.Val {
return root
}
// 查找左子树中是否存在p或q
leftCheck := lowestCommonAncestor(root.Left, p, q)
// 查找右子树中是否存在p或q
rightCheck := lowestCommonAncestor(root.Right, p, q)
// 如果左子树与右子树均查找到p或q,则p与q的公共祖先节点为当前节点,且当前节点必然是最近的公共祖先节点
if leftCheck != nil && rightCheck != nil {
return root
}
// 左子树未查找到p或q则两个节点的公共祖先节点为右子树中查找到的节点
if leftCheck == nil {
return rightCheck
}
return leftCheck
}