m2skills

print leafs bt python

Jun 13th, 2018
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.82 KB | None | 0 0
  1. # http://code2begin.blogspot.com
  2. # Program to print leaf nodes of binary tree
  3.  
  4. # node class
  5. class node:
  6.     def __init__(self, element):
  7.         self.data = element
  8.         self.left = None
  9.         self.right = None
  10.  
  11.  
  12. # function to print the leaf nodes of the binary tree
  13. def print_leaves(root):
  14.     if root is not None:
  15.         print_leaves(root.left)
  16.         if root.left is None and root.right is None:
  17.             print(root.data, end=" ")
  18.         print_leaves(root.right)
  19.  
  20.  
  21.  
  22. head = node(1)
  23. head.left = node(2)
  24. head.right = node(3)
  25. head.left.left = node(4)
  26. head.left.right = node(5)
  27. head.right.right = node(6)
  28. head.left.left.right = node(7)
  29. head.right.right.left = node(8)
  30. head.left.left.right.left = node(9)
  31. head.left.left.right.left.left = node(10)
  32. head.right.right.left.right = node(11)
  33. print("leaf nodes of the given tree are : ")
  34. print_leaves(head)
Add Comment
Please, Sign In to add comment