1. 题目
给定一个根为 root 的二叉树,每个结点的深度是它到根的最短距离。
如果一个结点在整个树的任意结点之间具有最大的深度,则该结点是最深的。
一个结点的子树是该结点加上它的所有后代的集合。
返回能满足“以该结点为根的子树中包含所有最深的结点”这一条件的具有最大深度的结点。
示例:
输入:[3,5,1,6,2,0,8,null,null,7,4]
输出:[2,7,4]
解释:
我们返回值为 2 的结点,在图中用黄色标记。
在图中用蓝色标记的是树的最深的结点。
输入 "[3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]" 是对给定的树的序列化表述。
输出 "[2, 7, 4]" 是对根结点的值为 2 的子树的序列化表述。
输入和输出都具有 TreeNode 类型。提示:
树中结点的数量介于 1 和 500 之间。
每个结点的值都是独一无二的。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/smallest-subtree-with-all-the-deepest-nodes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 解题
类似的题:LeetCode 1123. 最深叶节点的最近公共祖先(递归比较子树高度)
跟链接的题是一个意思,表述不太一样。
class Solution {
public:TreeNode* subtreeWithAllDeepest(TreeNode* root) {if(!root)return NULL;int hl = height(root->left);int hr = height(root->right);if(hl == hr)return root;else if(hl < hr)return subtreeWithAllDeepest(root->right);elsereturn subtreeWithAllDeepest(root->left);}int height(TreeNode* root){if(!root)return 0;return 1+max(height(root->left),height(root->right));}
};
上面解法,有很多冗余的重复遍历
- 优化
class Solution {
public:TreeNode* subtreeWithAllDeepest(TreeNode* root) {return dfs(root).second;}pair<int, TreeNode*> dfs(TreeNode* root)//返回深度,节点{if(!root)return {0, NULL};pair<int, TreeNode*> l = dfs(root->left);pair<int, TreeNode*> r = dfs(root->right);if(l.first == r.first)//左右高度一样,返回当前root,深度返回时都要+1return {l.first+1, root};else if(l.first > r.first)return {l.first+1, l.second};//左边高,返回左边找到的节点elsereturn {r.first+1, r.second};}
};