235.二叉搜索树的最近公共祖先

51 阅读1分钟

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

百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
算法:

func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
	// if root.Val == p.Val {
	// 	return p
	// }
	// if root.Val == q.Val {
	// 	return q
	// }
	min, max := p, q
	if min.Val > max.Val {
		min, max = q, p
	}
	return coreLowestCommonAncestor(root, min, max)
}

func coreLowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
	if root == nil {
		return nil
	}
	if p.Val <= root.Val && root.Val <= q.Val {
		return root
	}
	if root.Val < p.Val {
		return coreLowestCommonAncestor(root.Right, p, q)
	}
	return  coreLowestCommonAncestor(root.Left, p, q)
}