R. Simian
R. Simian

Reputation: 187

How can I get all child nodes of general tree in Python

My tree has the following structure: tree={'0':('1','2','3'), '1':('4'), '2':('5','6'), '3':(), '4':('7','8'), '8':('9','10','11')}

How can I wrote Python code to retrieve all given child nodes of a particular node? For example, if I give it node 4, the code should retrieve 7,8,9,10,11. For node 2, it should retrieve 5, 6 and so on.

I just started learning the basics of Python but I have no idea how to implement this for non-binary trees..

Upvotes: 1

Views: 3597

Answers (1)

Nick Reed
Nick Reed

Reputation: 5059

You can use a queue.

Once you've gotten the user's requested value, push it into the queue. Then, while the queue isn't empty, pop a value, print it, check the dict, and if the current value is a key in the dict, add each of those values to the queue to check them in the next pass.

import queue

tree={'0':('1','2','3'), '1':('4'), '2':('5','6'), '3':(), '4':('7','8'), '8':('9','10','11')}

num = input("what you want ")

q = queue.Queue()

q.put(num)

while not q.empty():
  n = q.get()
  for s in n:
    print(s)
    if s in tree:
      q.put(tree[s])

Demo

Note that if you have a tree tree={'0':('1'), '1':('0')}, or any other circular reference, this code will run forever. Be careful!

Upvotes: 2

Related Questions