剑指 Offer 68 - II. 二叉树的最近公共祖先

发布时间 2023-09-11 23:01:42作者: 小星code

题目链接: 剑指 Offer 68 - II. 二叉树的最近公共祖先

题目描述:

给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。

解法思路:

代码:

/**
 * 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 || root == p || root == q {
        return root
    }
    l := lowestCommonAncestor(root.Left,p,q)
    r := lowestCommonAncestor(root.Right,p,q)
    
    if l == nil {
        return r
    }
    if r == nil {
        return l
    }
    return root
  
}