Differences
This shows you the differences between two versions of the page.
| Both sides previous revision Previous revision | |||
|
pp:2025:scala:l03 [2025/03/16 22:43] cata_chiru |
pp:2025:scala:l03 [2025/03/28 12:04] (current) cata_chiru |
||
|---|---|---|---|
| Line 103: | Line 103: | ||
| case class Node(left: BinaryTree, info: Int, right: BinaryTree) extends BinaryTree { | case class Node(left: BinaryTree, info: Int, right: BinaryTree) extends BinaryTree { | ||
| - | override def toString: String = { | + | override def toString: String = { |
| - | def prettyPrint(tree: BinaryTree, depth: Int): String = { | + | def printTree( |
| - | tree match { | + | tree: BinaryTree, |
| - | case TVoid =>"\t" * (depth + 1) + tree.toString() + "\n" | + | prefix: String = "", |
| - | case Node(l, value, r) => | + | isLeft: Boolean = true |
| - | "\t" * (depth + 1) + value.toString() + "\n" + | + | ): String = |
| - | prettyPrint(l, depth+1) + prettyPrint(r, depth+1) | + | tree match { |
| - | } | + | case TVoid => |
| - | } | + | "" |
| + | case Node(l, value, r) => | ||
| + | val rightStr = | ||
| + | printTree(r, prefix + (if (isLeft && prefix.nonEmpty) "│ " else " "), isLeft = false) | ||
| + | val nodeStr = | ||
| + | prefix + (if (tree != this) if (isLeft) "└── " else "┌── " else " ") + value.toString + "\n" | ||
| + | val leftStr = | ||
| + | printTree(l, prefix + (if (isLeft) " " else "│ ")) | ||
| + | rightStr + nodeStr + leftStr | ||
| + | } | ||
| - | prettyPrint(this, 0) | + | '\n' + printTree(this) |
| - | } | + | } |
| } | } | ||
| </code> | </code> | ||