Answers for "leaf node"

1

leaf node

#A class that represents the individual node of the Binary tree
class node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.data = key

#A function to display the leaf nodes.
def counter(root):
    if root:
        if root.left==None and root.right==None:
            print(root.data)
        #First recur the left child
        if root.left:
            counter(root.left)
        #Recur the right child at last
        if root.right:
            counter(root.right)

def main():

    root = node(5)  #root node of the tree
    root.left = node(4) #node at left of root
    root.right = node(6) #node at right of root
    root.left.left = node(10)
    root.right.left = node(12)
    root.right.right =node(15)
    print('      ',root.data)
    print('      / \\')
    print('   ',root.left.data,'  ',root.right.data)
    print('    /   / \\')
    print(' ',root.left.left.data,'  ',root.right.left.data,root.right.right.data)
    print('The leaf nodes in the tree are = ')
    counter(root)

#Driver code
if __name__ == "__main__":
    main()
Posted by: Guest on July-03-2021

Browse Popular Code Answers by Language