Leetcode 865. Smallest Subtree with all the Deepest Nodes

这道题的关键在于知道每个节点的深度,可以用哈希表保存的前提下,怎么找出公共最小的父节点。方法是,如果当前node左右节点都有深度最大节点,返回当前node,如果只有左边有,返回node的左节点,反之返回右节点。也就是以下的java代码
public TreeNode answer(TreeNode node) {
if (node == null || depth.get(node) == max_depth)
return node;
TreeNode L = answer(node.left),
R = answer(node.right);
if (L != null && R != null) return node;
if (L != null) return L;
if (R != null) return R;
return null;
}

猜你喜欢

转载自www.cnblogs.com/bloomingFlower/p/9314903.html