Last active
April 29, 2021 21:04
-
-
Save novinfard/47f5ce94f518598a8ab1b51697b2b4e9 to your computer and use it in GitHub Desktop.
[Convert Binary tree input in AlgoExpert to tree input value]
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
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