2023-11-01 12:01:54 +0000 UTC

Lowest Common Ancestor of a Binary Tree

Code

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