Generic Trees
Generic Trees
Introduction
● In the previous modules, we discussed binary trees where each node can
have a maximum of two children and these can be represented easily with
two pointers i.e right child and left child.
● But suppose, we have a tree with many children for each node.
● If we do not know how many children a node can have, how do we represent
such a tree?
● For example, consider the tree shown below.
1
Generic Tree Node
● Implementation of a generic tree node in Python is quite simple.
● The node class will contain two attributes:
○ The node data
○ Since there can be a variable number of children nodes, thus the
second attribute will be a list of its children nodes. Each child is an
instance of the same node class. This is a general n-nary tree.
● Consider the given implementation of the Generic Tree Node class:
class GenericTreeNode:
def __init__ (self, data):
self.data = data #Node data
self.children = list() #List of children nodes
2
#Create nodes
n1= TreeNode(5)
n2 =TreeNode(2)
n3 =TreeNode(9)
n4 =TreeNode(8)
n5 =TreeNode(7)
n6 =TreeNode(15)
n7 =TreeNode(1)
def printTree(root):
#Not a base case but an edge case
if root == None:
return
3
def takeTreeInput():
print("Enter root Data")
rootData = int(input())#TAKE USER INPUT
if rootData == -1:#Stop taking inputs
return None
root = TreeNode(rootData)