Skip to content

Instantly share code, notes, and snippets.

@khanov
Last active July 14, 2021 02:17
Show Gist options
  • Select an option

  • Save khanov/4f1472b5ae001da817db to your computer and use it in GitHub Desktop.

Select an option

Save khanov/4f1472b5ae001da817db to your computer and use it in GitHub Desktop.
Binary Tree ASCII Printer
import Foundation
// Ideally Node should be a struct.
// However Swift doesn't allow recursive value types at the moment.
class Node {
var left, right: Node?
var value: String
init(value: String = "") {
self.value = value
}
func toString() -> String {
return buildTreeString(isTail: true)
}
private func buildTreeString(prefix: String = "", isTail: Bool) -> String {
var result = ""
if right != nil {
let newPrefix = prefix + (isTail ? "│ " : " ")
result += right!.buildTreeString(prefix: newPrefix, isTail: false)
}
result += prefix + (isTail ? "└── " : "┌── ") + value + "\n"
if left != nil {
let newPrefix = prefix + (isTail ? " " : "│ ")
result += left!.buildTreeString(prefix: newPrefix, isTail: true)
}
return result
}
}
// EXAMPLE
func buildExampleTree() -> Node {
let root = Node(value: "2")
let n11 = Node(value: "7")
let n12 = Node(value: "5")
let n21 = Node(value: "2")
let n22 = Node(value: "6")
let n23 = Node(value: "3")
let n24 = Node(value: "6")
let n31 = Node(value: "5")
let n32 = Node(value: "8")
let n33 = Node(value: "4")
let n34 = Node(value: "5")
let n35 = Node(value: "8")
let n36 = Node(value: "4")
let n37 = Node(value: "5")
let n38 = Node(value: "8")
root.left = n11
root.right = n12
n11.left = n21
n11.right = n22
n12.left = n23
n12.right = n24
n21.left = n31
n21.right = n32
n22.left = n33
n22.right = n34
n23.left = n35
n23.right = n36
n24.left = n37
n24.right = n38
return root
}
let tree = buildExampleTree()
println(tree.toString())
│ ┌── 8
│ ┌── 6
│ │ └── 5
│ ┌── 5
│ │ │ ┌── 4
│ │ └── 3
│ │ └── 8
└── 2
│ ┌── 5
│ ┌── 6
│ │ └── 4
└── 7
│ ┌── 8
└── 2
└── 5
@oliverfoggin
Copy link
Copy Markdown

This is excellent. Thanks 😄

@kezipe
Copy link
Copy Markdown

kezipe commented Mar 23, 2020

Excellent indeed. Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment