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.

答案

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

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,180评论 0 10
  • 20170522 “同频的快乐” 宝贝,最近妈妈写的情书,都不是给你的,宝贝表示被冷落,哈哈,妈妈有点博爱了,回归...
    春芸1216阅读 2,405评论 0 4
  • 世界上没有相同的两片叶子,世界上也没有另一个我,所以我是独一无二的,是绝版正品,不可复制,要活出自己最好的样子。 ...
    墨瞳_3611阅读 1,427评论 0 1
  • 六月份的四号和五号会有强降雨,晚上八点多的时候T君刚刚开完会,小雨的天空,等他到了我楼下,我下楼去找他的时候,雨...
    达芬齐_1c29阅读 1,450评论 3 0
  • CSS3过渡模块简单使用 示例: 鼠标悬停到div上的时候修改div宽度 记住以上三点就可以通过CSS3来做一个过...
    LiYajie阅读 3,101评论 0 1

友情链接更多精彩内容