码迷,mamicode.com
首页 > 其他好文 > 详细

865. Smallest Subtree with all the Deepest Nodes

时间:2020-02-06 11:07:31      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:hal   red   tput   air   sub   pac   get   write   style   

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.

Write a sub function deep(TreeNode root).
Return a pair(int depth, TreeNode subtreeWithAllDeepest)

 

In sub function deep(TreeNode root):

 

if root == null, return pair(0, null)
left = deep(root.left)
right = deep(root.left)

 

if left depth == right depth,
deepest nodes both in the left and right subtree,
return pair (left.depth + 1, root)

 

if left depth > right depth,
deepest nodes only in the left subtree,
return pair (left.depth + 1, left subtree)

 

if left depth < right depth,
deepest nodes only in the right subtree,
return pair (right.depth + 1, right subtree)

Complexity

Time O(N)
Space O(height)

 1 public TreeNode subtreeWithAllDeepest(TreeNode root) {
 2         return deep(root).getValue();
 3     }
 4 
 5     public Pair<Integer, TreeNode> deep(TreeNode root) {
 6         if (root == null) return new Pair(0, null);
 7         Pair<Integer, TreeNode> l = deep(root.left), r = deep(root.right);
 8 
 9         int d1 = l.getKey(), d2 = r.getKey();
10         return new Pair(Math.max(d1, d2) + 1, d1 == d2 ? root : d1 > d2 ? l.getValue() : r.getValue());
11     }

 

865. Smallest Subtree with all the Deepest Nodes

标签:hal   red   tput   air   sub   pac   get   write   style   

原文地址:https://www.cnblogs.com/beiyeqingteng/p/12267549.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!