给定一个根为 root 的二叉树,每个节点的深度是 该节点到根的最短距离 。
如果一个节点在 整个树 的任意节点之间具有最大的深度,则该节点是 最深的 。
一个节点的 子树 是该节点加上它的所有后代的集合。
返回能满足 以该节点为根的子树中包含所有最深的节点 这一条件的具有最大深度的节点。
注意:本题与力扣 1123 重复:https://leetcode-cn.com/problems/lowest-common-ancestor-of-deepest-leaves/
输入:root = [3,5,1,6,2,0,8,null,null,7,4]
输出:[2,7,4]
解释:
我们返回值为 2 的节点,在图中用黄色标记。
在图中用蓝色标记的是树的最深的节点。
注意,节点 5、3 和 2 包含树中最深的节点,但节点 2 的子树最小,因此我们返回它。
示例 2:
输入:root = [1]
输出:[1]
解释:根节点是树中最深的节点。
示例 3:
输入:root = [0,1,3,null,2]
输出:[2]
解释:树中最深的节点为 2 ,有效子树为节点 2、1 和 0 的子树,但节点 2 的子树最小。
提示:
树中节点的数量介于 1 和 500 之间。
0 <= Node.val <= 500
每个节点的值都是独一无二的。
class Solution {
int max_Depth;//记录最大深度
Map<TreeNode, Integer> depth;//存储每个节点对应的深度
public TreeNode subtreeWithAllDeepest(TreeNode root) {
depth = new HashMap<>();
depth.put(null, -1);
dfs(root, null);//获得所有的深度
max_Depth = -1;
for(Integer num : depth.values()){
//原来可以直接遍历value
max_Depth = Math.max(max_Depth, num);
}
//再做一次深度搜索,确定答案
return answer(root);
}
void dfs(TreeNode root, TreeNode parent){
//增加parent遍历,便于遍历,有点新
if(root != null){
depth.put(root, depth.get(parent) + 1);
dfs(root.left, root);
dfs(root.right, root);
}
}
TreeNode answer(TreeNode root){
if(root == null || depth.get(root) == max_Depth){
//恰好为最大深度,直接返回
return root;
}
//对左右节点进行访问,根据其返回结果决定返回什么
TreeNode L = answer(root.left);
TreeNode R = answer(root.right);//有点像后序遍历
if(L != null && R != null) return root;//左右节点满足,则直接返回当前节点
if(L != null) return L;
if(R != null) return R;//任意为空,返回另一个
return null;//都为空,就返回null
}
}
2.便于理解的方式,大体框架时一致 的
思路:从每个树开始,获得当前节点的左右子树的最大深度
深度相同,说明最深的节点在这个节点两边,那这个节点就是结果
如果深度不相同,则去深度大的子树继续判断,最终就能得到结果
class Solution {
public TreeNode subtreeWithAllDeepest(TreeNode root) {
if(root == null) return root;
//获取当前节点的最大深度
int leftMaxDepth = getMaxDepth(root.left);
int rightMaxDepth = getMaxDepth(root.right);
//若两端深度相同,则就是这个节点
if(leftMaxDepth == rightMaxDepth) return root;
//若不相同,则在深度达的子树寻找
if(leftMaxDepth < rightMaxDepth) {
return subtreeWithAllDeepest(root.right);
}else {
return subtreeWithAllDeepest(root.left);
}
}
//常见的获取深度方法
public int getMaxDepth(TreeNode root){
if(root == null) return 0;
return Math.max(getMaxDepth(root.left), getMaxDepth(root.right)) + 1;
//注意+1是在最外面的
}
}