|
| 1 | +# Author: Parameswaran |
| 2 | + |
| 3 | +# sample object |
| 4 | +classSample: |
| 5 | +def__init__(self,data_description,node_id,parent_id=""): |
| 6 | +self.data_description=data_description |
| 7 | +self.node_id=node_id |
| 8 | +self.parent_id=parent_id |
| 9 | + |
| 10 | + |
| 11 | +# Node structure (Basically N-ary Tree) |
| 12 | +classNode: |
| 13 | +def__init__(self,data): |
| 14 | +self.data=Sample(data['data_description'],data['node_id'],data['parent_id']) |
| 15 | +self.children= [] |
| 16 | + |
| 17 | + |
| 18 | +classTree: |
| 19 | +def__init__(self,data): |
| 20 | +self.Root=data |
| 21 | + |
| 22 | +definsert_child(self,root,new_node): |
| 23 | + |
| 24 | +# if the list item's parent_id is equal to the current node it will append the node in their child array. |
| 25 | + |
| 26 | +ifroot.data.node_id==new_node.data.parent_id: |
| 27 | +root.children.append(new_node) |
| 28 | + |
| 29 | +# else it will check all the node and their children list whether the parent_id is same. |
| 30 | + |
| 31 | +eliflen(root.children)>0: |
| 32 | +foreach_childinroot.children: |
| 33 | +# it will create a recursive call for all nodes to treate as a root and search for all its child_list nodes |
| 34 | +self.insert_child(each_child,new_node) |
| 35 | + |
| 36 | +defprint_tree(self,root,point): |
| 37 | +print(point,root.data.node_id,root.data.parent_id,root.data.data_description) |
| 38 | +iflen(root.children)>0: |
| 39 | +point+="_" |
| 40 | +foreach_childinroot.children: |
| 41 | +self.print_tree(each_child,point) |
| 42 | + |
| 43 | + |
| 44 | +data= {'data_description':'Sample_root_1','node_id':'1','parent_id':''} |
| 45 | +data1= {'data_description':'Sample_root_2','node_id':'2','parent_id':'1'} |
| 46 | +data2= {'data_description':'Sample_root_3','node_id':'3','parent_id':'1'} |
| 47 | +data3= {'data_description':'Sample_root_4','node_id':'4','parent_id':'2'} |
| 48 | +data4= {'data_description':'Sample_root_5','node_id':'5','parent_id':'3'} |
| 49 | +data5= {'data_description':'Sample_root_6','node_id':'6','parent_id':'4'} |
| 50 | +data6= {'data_description':'Sample_root_7','node_id':'7','parent_id':'4'} |
| 51 | + |
| 52 | +a=Tree(Node(data)) |
| 53 | +a.insert_child(a.Root,Node(data1)) |
| 54 | +a.insert_child(a.Root,Node(data2)) |
| 55 | +a.insert_child(a.Root,Node(data3)) |
| 56 | +a.insert_child(a.Root,Node(data4)) |
| 57 | +a.insert_child(a.Root,Node(data5)) |
| 58 | +a.insert_child(a.Root,Node(data6)) |
| 59 | +a.print_tree(a.Root,"|_") |
| 60 | + |
| 61 | +# |_ 1 Sample_root_1 |
| 62 | +# |__ 2 1 Sample_root_2 |
| 63 | +# |___ 4 2 Sample_root_4 |
| 64 | +# |____ 6 4 Sample_root_6 |
| 65 | +# |____ 7 4 Sample_root_7 |
| 66 | +# |__ 3 1 Sample_root_3 |
| 67 | +# |___ 5 3 Sample_root_5 |