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:

865. Smallest Subtree with all the Deepest Nodes_第1张图片

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 deep(TreeNode root) {
 6         if (root == null) return new Pair(0, null);
 7         Pair 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)