题目描述
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
解题思路
基于前一题的解题思路Leetcode274 H指数,可以把查找H指数的过程改成二分法,因为此题中H指数数组是已经排序好的,这样就可以实现log(N)时间复杂度。
代码实现
public static int hIndex(int[] citations) {int s = 0, e = citations.length - 1, r = citations[0] > 0 ? 1 : 0;while (s < e) {int mid = (s + e) / 2;if (citations[mid] >= citations.length - mid) {r = citations.length - mid;e = mid;} else {s = mid + 1;}}// 防止出现特殊情况没有扫描到if (citations[s] >= citations.length - s && (citations.length - s) > r) {r = citations.length - s;}return r;}