前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 865. 具有所有最深结点的最小子树(递归)

LeetCode 865. 具有所有最深结点的最小子树(递归)

作者头像
Michael阿明
发布2020-07-13 15:34:55
4180
发布2020-07-13 15:34:55
举报

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);
		else
    		return 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,深度返回时都要+1
            return {l.first+1, root};
        else if(l.first > r.first)
            return {l.first+1, l.second};//左边高,返回左边找到的节点
        else
            return {r.first+1, r.second};
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-04-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 题目
  • 2. 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档