I find it difficult to complicate the dictionary as follows: the given input number 5, then the search key=5in the dictionary placed it first, and then its first value 4and find key=4in the dictionary and put its value as the second, and then the second value 5, which 3, and find key=3in the dictionary and place it value as third
Values will consist of one or two integers
I am working on drawing a binary tree, so it will be easier if the root node (parent), which is 5 here, is first, and then its children, children, etc. next
I tried to organize it using OrderedDict, but I could not find it
Can someone help me?
Input:
{8: [9], 3: [6, 8], 4: [2, 1], 5: [4, 3], 6: [0, 7]}
Output:
{5: [4, 3], 4: [2, 1], 3: [6, 8], 6: [0, 7], 8: [9]}
Updated code:
def dfs(cur, prev, edges, res):
for next in edges[cur]:
if next == prev: continue
res.setdefault(cur, []).append(next)
dfs(next, cur, edges, res)
def construct_tree(edges, root):
d = {}
x = []
for edge in edges:
u, v = edge
d.setdefault(u, []).append(v)
d.setdefault(v, []).append(u)
res = {}
dfs(root, -1, d, res)
return res
if __name__ == '__main__':
root_node = 5
edges = [[2, 4], [4, 1], [0, 6], [7, 6], [8, 9], [4, 5], [6, 3], [3, 5], [3, 8]]
print((construct_tree(edges, root_node)))