题目地址:
https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/
给定一棵二叉树,求其最深的叶子的最近公共祖先。
思路是DFS。先开一个新的class,存树的节点和它所在的深度。接着开始做DFS。我们定义一个方法,返回参数节点为根的子树的最深叶子的最近公共祖先,如果不存在,则返回null。如果是空树,则返回null;接下来递归求解左子树的最深叶子的最近公共祖先和右子树的最深叶子的最近公共祖先,如果两个返回值都是null,那么说明左右都是空树,说明本身就是叶子,那就返回自己,并把自己所在的层数也一并返回给上层;如果恰好有一个子树非空,那就返回那个不空的那一侧的返回值;如果都非空,则看一下左右子树的最深叶子的深度,如果不一样深,那要返回那个更深的子树对应的返回值,如果一样深,那么当前节点就是本节点为根的子树的最深叶子的最近公共祖先,则返回自己,以及叶子的最深深度(层数)。代码如下:
public class Solution {
class Pair {
int depth;
TreeNode node;
public Pair(int depth, TreeNode node) {
this.depth = depth;
this.node = node;
}
}
public TreeNode lcaDeepestLeaves(TreeNode root) {
if (root == null) {
return null;
}
return dfs(root, 0).node;
}
// 返回以cur为树根的子树的最深叶子的最近公共祖先,以及最深叶子的层数;
// depth是当前节点cur的层数
private Pair dfs(TreeNode cur, int depth) {
if (cur == null) {
return null;
}
Pair left = dfs(cur.left, depth + 1), right = dfs(cur.right, depth + 1);
// 当前是叶子,则返回当前节点和其层数
if (left == null && right == null) {
return new Pair(depth, cur);
}
if (left == null) {
return right;
}
if (right == null) {
return left;
}
// 左右子树的最深叶子深度一样,那么cur就是它们的最近公共祖先
if (left.depth == right.depth) {
left.node = cur;
return left;
}
if (left.depth > right.depth) {
return left;
} else {
return right;
}
}
}
class TreeNode {
int val;
TreeNode left, right;
public TreeNode(int val) {
this.val = val;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( h ) O(h) O(h)。