Description

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:

[leetcode] 865. Smallest Subtree with all the Deepest Nodes_结点

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.

Note:

  • The number of nodes in the tree will be between 1 and 500.
  • The values of each node are unique.

分析

题目的意思是:给定一个根为 root 的二叉树,每个结点的深度是它到根的最短距离。如果一个结点在整个树的任意结点之间具有最大的深度,则该结点是最深的。一个结点的子树是该结点加上它的所有后代的集合。
返回能满足“以该结点为根的子树中包含所有最深的结点”这一条件的具有最大深度的结点。

  • 二叉树一般就是递归,思路很直接,代码很简洁,用到pair把深度和root回传。

代码

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* subtreeWithAllDeepest(TreeNode* root) {

return solve(root).second;
}
pair<int,TreeNode*> solve(TreeNode* root){
if(!root) return {0,root};
auto l=solve(root->left);
auto r=solve(root->right);
if(l.first==r.first) return {1+l.first,root};
else if(l.first>r.first) return {1+l.first,l.second};
else return {1+r.first,r.second};
}
};

参考文献

​866. Smallest Subtree with all the Deepest Nodes​​​​Smallest Subtree with all the Deepest Nodes 具有所有最深结点的最小子树​