Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR SHELL

python tree

class TreeNode:
    def __init__(self, data):
        self.data = data
        self.children = []
        self.parent = None

    def add_child(self, child):
        child.parent = self
        self.children.append(child)

    def print_tree(self):
        print(self.data)
        if self.children:
            for child in self.children:
                child.print_tree()

    def get_level(self):
        level = 0
        p = self.parent
        while p:
            level += 1
            p = p.parent
        return level


def build_product_tree():
    root = TreeNode('Electronics')

    laptop = TreeNode('Laptop')
    laptop.add_child(TreeNode('Thinkpad'))
    laptop.add_child(TreeNode('Surface'))
    laptop.add_child(TreeNode('Mac'))

    cellphone = TreeNode('Cellphone')
    cellphone.add_child(TreeNode('iphone'))
    cellphone.add_child(TreeNode('google pixel'))
    cellphone.add_child(TreeNode('vivo'))

    tv = TreeNode('Television')
    tv.add_child(TreeNode('samsung'))
    tv.add_child(TreeNode('lg'))

    root.add_child(laptop)
    root.add_child(cellphone)
    root.add_child(tv)

    root.print_tree()
 
PREVIOUS NEXT
Tagged: #python #tree
ADD COMMENT
Topic
Name
9+3 =