Last active
November 24, 2015 22:55
-
-
Save shepting/8d7d34ebbb024447bb6c to your computer and use it in GitHub Desktop.
Print out a tree of nodes with multiple children each.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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