865. Smallest Subtree with all the Deepest Nodes
Posted beiyeqingteng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了865. 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.
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的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 865. Smallest Subtree with all the Deepest Nodes
866. Smallest Subtree with all the Deepest Nodes
Given a tree, find the smallest subtree that contains all of the tree's deepest nodes