leetcode 865. Smallest Subtree with all the Deepest Nodes(包含最深点的最小子树)

本文介绍了一种算法,用于查找二叉树中包含所有最深节点的最小子树。通过递归计算树的高度,并返回包含最深节点的子树根节点。文章通过实例解释了如何确定最深节点及其子树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given the root of a binary tree, the depth of each node is the shortest distance to the root.

Return the smallest subtree such that it contains all the deepest nodes in the original tree.

A node is called the deepest if it has the largest depth possible among any node in the entire tree.

The subtree of a node is tree consisting of that node, plus the set of all descendants of that node.

Note: This question is the same as 1123: https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/

Example 1:
在这里插入图片描述
Input: root = [3,5,1,6,2,0,8,null,null,7,4]
Output: [2,7,4]
Explanation: We return the node with value 2, colored in yellow in the diagram.
The nodes coloured in blue are the deepest nodes of the tree.
Notice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2 is the smallest subtree among them, so we return it.

找出包含最深点的最小子树,最深点是指到root的距离最远。

思路:
可按求树的高度计算,但是返回高度的同时还要返回包含最深点的最小树的root
如果左右子树的高度相同,那么当前root就可能是最小树的root
如果左子树高度>右子树高度,那当前root就不是最小树的root,最小树在左子树上,返回时root就是左子树返回的root

因为又要返回高度,又要返回最小树的root,可以定义一个class,包含这两个成员,当然也可以返回一个Object数组,取值时用down cast

    public TreeNode subtreeWithAllDeepest(TreeNode root) {
        if(root == null) return null;
        return (TreeNode)(height(root)[1]);
    }
    
    Object[] height(TreeNode root) {
        if(root == null) {
            return new Object[]{-1, root};
        }
        
        Object[] left = height(root.left);
        Object[] right = height(root.right);
        
        int leftH = ((Integer)left[0]).intValue();
        int rightH = ((Integer)right[0]).intValue();
        
        if(leftH > rightH) {
            return new Object[]{leftH+1, left[1]};
        } else if(leftH < rightH) {
            return new Object[]{rightH+1, right[1]};
        }
        
        return new Object[]{leftH+1, root};
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值