|
| 1 | +package mtree |
| 2 | + |
| 3 | +// P70 (**) Tree construction from a node string. |
| 4 | +// |
| 5 | +// We suppose that the nodes of a multiway tree contain single characters. |
| 6 | +// In the depth-first order sequence of its nodes, a special character ^ |
| 7 | +// has been inserted whenever, during the tree traversal, the move is a |
| 8 | +// backtrack to the previous level. |
| 9 | +// |
| 10 | +// By this rule, the tree in the figure opposite is represented as: |
| 11 | +// |
| 12 | +// afg^^c^bd^e^^^ |
| 13 | +// Define the syntax of the string and write a function string2MTree to construct |
| 14 | +// an MTree from a String. Make the function an implicit conversion from String. |
| 15 | +// Write the reverse function, and make it the toString method of MTree. |
| 16 | +// |
| 17 | +// scala> MTree('a', List(MTree('f', List(MTree('g'))), MTree('c'), MTree('b', List(MTree('d'), MTree('e'))))).toString |
| 18 | +// res0: String = afg^^c^bd^e^^^ |
| 19 | +object P70: |
| 20 | + def string2MTree(s: String): MTree[Char] = |
| 21 | + /* |
| 22 | + First recursive dfs call collects the children, |
| 23 | + second recursive dfs call collects the siblings. |
| 24 | +
|
| 25 | + x=g, xs=^^c^bd^e^^^, ys=^c^bd^e^^^, zs=c^bd^e^^^ |
| 26 | + x=e, xs=^^^, ys=^^, zs=^ |
| 27 | + x=d, xs=^e^^^, ys=e^^^, zs=^ |
| 28 | + x=b, xs=d^e^^^, ys=^, zs= |
| 29 | + x=c, xs=^bd^e^^^, ys=bd^e^^^, zs= |
| 30 | + x=f, xs=g^^c^bd^e^^^, ys=c^bd^e^^^, zs= |
| 31 | + x=a, xs=fg^^c^bd^e^^^, ys=, zs= |
| 32 | + */ |
| 33 | + def loop(s: String): (List[MTree[Char]], String) = |
| 34 | + s match |
| 35 | + case "" => (Nil, "") |
| 36 | + case s"^$xs" => (Nil, xs) |
| 37 | + case _ => |
| 38 | + val (x, xs) = (s.head, s.tail) |
| 39 | + val (children, ys) = loop(xs) |
| 40 | + val (siblings, zs) = loop(ys) |
| 41 | + (MTree(x, children) :: siblings, zs) |
| 42 | + |
| 43 | + loop(s)._1.head |
| 44 | + |
| 45 | + def tree2String(t: MTree[Char]): String = |
| 46 | + def loop(acc: DList[Char], t: MTree[Char]): DList[Char] = |
| 47 | + val xs = t.children.foldLeft(DList.empty[Char])(loop) |
| 48 | + val ys = DList.singleton(t.value) ++ xs ++ DList.singleton('^') |
| 49 | + acc ++ ys |
| 50 | + |
| 51 | + loop(DList.empty[Char], t).toList.mkString |
0 commit comments