Skip to content

Instantly share code, notes, and snippets.

@novinfard
Last active April 29, 2021 21:04
Show Gist options
  • Save novinfard/47f5ce94f518598a8ab1b51697b2b4e9 to your computer and use it in GitHub Desktop.
Save novinfard/47f5ce94f518598a8ab1b51697b2b4e9 to your computer and use it in GitHub Desktop.
[Convert Binary tree input in AlgoExpert to tree input value]
class Program {
class BST {
var value: Int
var left: BST?
var right: BST?
init(value: Int) {
self.value = value
}
}
}
// Converter
let treeJson =
"""
{
"nodes": [
{"id": "1", "left": "2", "right": "3", "value": 1},
{"id": "2", "left": "4", "right": "5", "value": 2},
{"id": "3", "left": "6", "right": "7", "value": 3},
{"id": "4", "left": "8", "right": "9", "value": 4},
{"id": "5", "left": "10", "right": null, "value": 5},
{"id": "6", "left": null, "right": null, "value": 6},
{"id": "7", "left": null, "right": null, "value": 7},
{"id": "8", "left": null, "right": null, "value": 8},
{"id": "9", "left": null, "right": null, "value": 9},
{"id": "10", "left": null, "right": null, "value": 10}
],
"root": "1"
}
"""
let jsonData = Data(treeJson.utf8)
let decoder = JSONDecoder()
let trees = try! decoder.decode(BSTJson.self, from: jsonData)
var inputHash = [String: Program.BST]()
trees.nodes.forEach {
inputHash[$0.id] = Program.BST(value: $0.value)
}
inputHash.forEach { input in
guard let node = trees.nodes.first(where: { $0.value == input.value.value }) else { return }
if let right = node.right {
input.value.right = inputHash[right]
}
if let left = node.left {
input.value.left = inputHash[left]
}
}
let input = inputHash.values.first(where: { Int(trees.root) == $0.value})!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment