forked from reingart/exercism
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtree_building.py
50 lines (46 loc) · 1.56 KB
/
tree_building.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Record:
def __init__(self, record_id, parent_id):
self.record_id = record_id
self.parent_id = parent_id
class Node:
def __init__(self, node_id):
self.node_id = node_id
self.children = []
def BuildTree(records):
root = None
records.sort(key=lambda x: x.record_id)
ordered_id = [i.record_id for i in records]
if records:
if ordered_id[-1] != len(ordered_id) - 1:
raise ValueError('broken tree')
if ordered_id[0] != 0:
raise ValueError('invalid')
trees = []
parent = {}
for i in range(len(ordered_id)):
for j in records:
if ordered_id[i] == j.record_id:
if j.record_id == 0:
if j.parent_id != 0:
raise ValueError('error!')
if j.record_id < j.parent_id:
raise ValueError('something went wrong!')
if j.record_id == j.parent_id:
if j.record_id != 0:
raise ValueError('error!')
trees.append(Node(ordered_id[i]))
for i in range(len(ordered_id)):
for j in trees:
if i == j.node_id:
parent = j
for j in records:
if j.parent_id == i:
for k in trees:
if k.node_id == 0:
continue
if j.record_id == k.node_id:
child = k
parent.children.append(child)
if len(trees) > 0:
root = trees[0]
return root