Leetcode865 - Smallest Subtree with all the Deepest Nodes

题目

Given a binary tree rooted at root, the depth of each node is the shortest distance to the root.

A node is deepest if it has the largest depth possible among any node in the entire tree.

The subtree of a node is that node, plus the set of all descendants of that node.

Return the node with the largest depth such that it contains all the deepest nodes in its subtree.

Example 1:

Input: [3,5,1,6,2,0,8,null,null,7,4]
Output: [2,7,4]
Explanation:

We return the node with value 2, colored in yellow in the diagram.
The nodes colored in blue are the deepest nodes of the tree.
The input "[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]" is a serialization of the given tree.
The output "[2, 7, 4]" is a serialization of the subtree rooted at the node with value 2.
Both the input and output have TreeNode type.


思路:

包含所有最深叶子结点的最小子树必然包含这样的特点,它的左右子树的高度相同。所以需要使用递归查找最深的深度,然后在进行判断当左右子树的高度相同的时候记录下当前子树的根结点。同时不要忘记更新最深深度。


代码:

int max = 0;
TreeNode res = null;
public TreeNode subtreeWithAllDeepest(TreeNode root) {
    if(root == null){
        return null;
    }
    dfs(root, 0);
    return res;
}
    
private int dfs(TreeNode root, int level){
    if(root == null){
        return level;
    }
    int left = dfs(root.left, level + 1);
    int right = dfs(root.right, level + 1);
    if(left == right && left >= max){
        res = root;
        max = left;
    }
    return Math.max(left, right);
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 只是路过,却也成了别人的踏板
    訫聞不訫阅读 1,643评论 0 0
  • 雨滴青萍光潋舟,倩影悠悠,琴瑟吹心。 婆娑烟紫乱花衣,惊梦平生,一段香残。 红泪盈盈钗凤娟,纸伞飘飘,萧...
    逆光之旅阅读 1,580评论 0 0
  • 如果你问我是谁,我会首先告诉你我是一个女人,一个幸福的女人,一个有着美满家庭的幸福女人,一个有着美满家庭、做着自己...
    穆珊珊阅读 2,953评论 0 3
  • 阴天,平淡,关于身体大脑常用常新。 已知有权威机构发表常用大脑可以有效的预防衰老,不易得老年痴呆等老年大脑常得疾病...
    生虎日记阅读 3,821评论 0 1

友情链接更多精彩内容