【scala】含有list子集的递归方法记录层数深度

[复制链接]
发表于 2025-11-8 22:41:43 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
样例使用scala语言编写。
特点:
RecursiveData对象中包罗一个成员child含有多个RecursiveData子对象。
思绪:
递归方法中传入一个:int作为parent的深度,传入一个set记录以是深度聚集。
同一深度int+1不会影响雷同深度的效果,set又可以将同一深度层去重。
容易犯错误:使用单独对象记录,应为是递归是树形布局,随着层数和枝叶增长,会多盘算,如recWrong方法就是错误范例。
  1. import org.scalatest.funsuite.AnyFunSuite
  2. import java.util.concurrent.atomic.AtomicInteger
  3. import scala.collection.mutable
  4. case class RecursiveData(name: String, child: List[RecursiveData])
  5. class RecursiveTest extends AnyFunSuite {
  6.   val r41 = RecursiveData("41", List.empty)
  7.   val r42 = RecursiveData("42", List.empty)
  8.   val r43 = RecursiveData("43", List.empty)
  9.   val r44 = RecursiveData("44", List.empty)
  10.   val r31 = RecursiveData("31", List(r41, r42))
  11.   val r32 = RecursiveData("32", List(r43, r44))
  12.   val r33 = RecursiveData("33", List.empty)
  13.   val r34 = RecursiveData("34", List.empty)
  14.   val r35 = RecursiveData("35", List.empty)
  15.   val r36 = RecursiveData("36", List.empty)
  16.   val r37 = RecursiveData("37", List.empty)
  17.   val r21 = RecursiveData("21", List(r31, r32, r33))
  18.   val r22 = RecursiveData("22", List(r34, r35))
  19.   val r23 = RecursiveData("23", List(r36, r37))
  20.   val r11 = RecursiveData("11", List(r21, r22, r23))
  21.   def rec(data: RecursiveData, parentDepth: Int, depths: mutable.Set[Integer]): Unit = {
  22.     val currDepth = parentDepth + 1
  23.     depths.add(currDepth)
  24.     data.child.foreach(c => {
  25.       rec(c, currDepth, depths)
  26.     })
  27.   }
  28.   test("test-recursive-right") {
  29.     val depths: mutable.Set[Integer] = mutable.Set.empty
  30.     rec(r11, 0, depths)
  31.     println(s"current depths:${depths},and max depths:${depths.max}")
  32.     // current depths:Set(1, 2, 3, 4),and max depths:4
  33.   }
  34.   def recWrong(data: RecursiveData, depth: AtomicInteger): Unit = {
  35.     data.child.foreach(c => {
  36.       recWrong(c, depth)
  37.     })
  38.     if (data.child.nonEmpty) {
  39.       // 错误思路: 每次增加减去相应的子成员增加量
  40.       depth.set(depth.get() - (data.child.size - 1))
  41.     }
  42.     depth.getAndIncrement()
  43.   }
  44.   test("test-recursive-wrong") {
  45.     val depth: AtomicInteger = new AtomicInteger
  46.     recWrong(r11, depth)
  47.     println(depth)
  48.     // 7
  49.   }
  50. }
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表