865. 具有所有最深结点的最小子树

给定一个根为 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 类型。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/smallest-subtree-with-all-the-deepest-nodes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

1.
class Solution {
public:
    int depth(TreeNode* root) {
        if (root == NULL) return 0;
        return max(depth(root->left), depth(root->right)) + 1;
    }
    TreeNode* subtreeWithAllDeepest(TreeNode* root) {
        if (root == NULL) return root;
        int dl = depth(root->left);
        int dr = depth(root->right);
        if (dl == dr) return root;
        if (dl > dr) return subtreeWithAllDeepest(root->left);
        return subtreeWithAllDeepest(root->right);
    }
};

作者:da-li-wang
链接:https://leetcode-cn.com/problems/smallest-subtree-with-all-the-deepest-nodes/solution/c-jian-dan-di-gui-by-da-li-wang-7/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
2.
class Solution {
public:
    pair<int, TreeNode*> dfs(TreeNode* root, int d) {
        if (root == NULL) return {-1, root};
        if (root->left == NULL && root->right == NULL) return {d, root};
        auto pl = dfs(root->left, d + 1);
        auto pr = dfs(root->right, d + 1);
        if (pl.first < pr.first) return pr;
        if (pl.first > pr.first) return pl;
        return {pl.first, root};
    }
    TreeNode* subtreeWithAllDeepest(TreeNode* root) {
        return dfs(root, 0).second;
    }
};

作者:da-li-wang
链接:https://leetcode-cn.com/problems/smallest-subtree-with-all-the-deepest-nodes/solution/c-jian-dan-di-gui-by-da-li-wang-7/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值