Leetcode—865. 具有所有最深节点的最小子树【中等】

2025每日刷题(236)

Leetcode---865. 具有所有最深节点的最小子树

实现代码

go 复制代码
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func subtreeWithAllDeepest(root *TreeNode) *TreeNode {
    type pair struct {
        node *TreeNode
        depth int
    }

    var dfs func(root *TreeNode) pair
    dfs = func(root *TreeNode) pair {
        if root == nil {
            return pair{nil, 0}
        }

        lt, rt := dfs(root.Left), dfs(root.Right)
        ld, rd := lt.depth, rt.depth

        if(ld > rd) {
            return pair{lt.node, ld + 1}
        } 

        if(ld < rd) {
            return pair{rt.node, rd + 1}
        }
        return pair{root, ld + 1}
    }
    return dfs(root).node
}

运行结果

之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
早日退休!!!几秒前
进程与线程的上下文加载_保存及内存映射
开发语言
jllllyuz2 分钟前
MATLAB实现蜻蜓优化算法
开发语言·算法·matlab
上进小菜猪2 分钟前
基于 YOLOv8 的智能杂草检测识别实战 [目标检测完整源码]
后端
AlenTech3 分钟前
208. 实现 Trie (前缀树) - 力扣(LeetCode)
leetcode
iAkuya4 分钟前
(leetcode)力扣100 36二叉树的中序遍历(迭代递归)
算法·leetcode·职场和发展
wangwangmoon_light12 分钟前
1.1 LeetCode总结(线性表)_枚举技巧
算法·leetcode·哈希算法
冰暮流星17 分钟前
javascript逻辑运算符
开发语言·javascript·ecmascript
flysh0518 分钟前
如何利用 C# 内置的 Action 和 Func 委托
开发语言·c#
码农小韩39 分钟前
基于Linux的C++学习——动态数组容器vector
linux·c语言·开发语言·数据结构·c++·单片机·学习
木风小助理40 分钟前
`mapfile`命令详解:Bash中高效的文本至数组转换工具
开发语言·chrome·bash