Skip to content

Instantly share code, notes, and snippets.

@shepting
Last active November 24, 2015 22:55
Show Gist options
  • Save shepting/8d7d34ebbb024447bb6c to your computer and use it in GitHub Desktop.
Save shepting/8d7d34ebbb024447bb6c to your computer and use it in GitHub Desktop.
Print out a tree of nodes with multiple children each.
//
// main.swift
// NodeTraversal
//
// Created by Steven Hepting on 11/16/15.
// Copyright © 2015 Steven Hepting. All rights reserved.
// Algorithm from http://bit.ly/1kSdSvc
//
import Foundation
class Node {
var value: String = ""
var children: [Node]?
init(_ value: String, children: [Node]? = nil) {
self.value = value
self.children = children
}
func printNode() {
printNode(prefix: "", isLast: true)
}
func printNode(prefix prefix: String = "", isLast: Bool) {
let indicator = isLast ? "└──" : "├──"
print("\(prefix)\(indicator) \(value)")
guard let children = children else { return }
for (index, child) in children.enumerate() {
let isLastChild = index == (children.count - 1)
let childIndicator = isLast ? " " : "│ "
child.printNode(prefix: "\(prefix)\(childIndicator)", isLast: isLastChild)
}
}
}
print("Hello, World!")
let a = Node("a")
let b = Node("b")
let c = Node("c", children: [a, b])
let d = Node("d")
let asdf = Node("asdf")
let e = Node("e", children: [asdf])
let f = Node("f")
let z = Node("z", children: [c, d, e, f])
z.printNode()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment