You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Racket/Scheme无结构节点下编写树递归depth函数求解树最大层级

实现思路
  • 边界条件:输入为空列表'()时直接返回0,匹配基础用例要求
  • 元素递归处理:遍历列表的每个元素,如果是子列表就递归计算它的深度,非列表的原子元素深度贡献为0
  • 层级计算:当前列表的深度等于1(当前层本身占1层)加上所有子元素的深度最大值
完整实现代码
(define (depth tree)
  (if (null? tree)
      0
      (+ 1
         (apply max
                (map (lambda (node)
                       (if (list? node)
                           (depth node)
                           0))
                     tree)))))
用例验证

给出的四个测试用例运行结果完全匹配预期:

  • (depth '()) => 0
  • (depth '(1 2 3)) => 1
  • (depth '(a (b (c (d))))) => 4
  • (depth '((((((0))))))) => 6

内容的提问来源于stack exchange,提问作者Ptechnic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 19:15:04