m2skills

boundary traversal python

Jun 13th, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. # http://code2begin.blogspot.com
  2. # program to print boundary traversal of a given binary tree
  3.  
  4.  
  5. # node class
  6. class node:
  7.     def __init__(self, element):
  8.         self.data = element
  9.         self.left = None
  10.         self.right = None
  11.  
  12.  
  13. # function to print the left boundary of the tree
  14. def print_left_boundary(root):
  15.     if root is not None:
  16.         if root.left is not None:
  17.             print(root.data, end=" ")
  18.             print_left_boundary(root.left)
  19.         elif root.right is not None:
  20.             print(root.data, end=" ")
  21.             print_left_boundary(root.right)
  22.     return
  23.  
  24.  
  25. # function to print the left boundary of the tree
  26. def print_right_boundary(root):
  27.     if root is not None:
  28.         if root.right is not None:
  29.             print_right_boundary(root.right)
  30.             print(root.data, end=" ")
  31.         elif root.left is not None:
  32.             print_right_boundary(root.left)
  33.             print(root.data, end=" ")
  34.     return
  35.  
  36.  
  37. # function to print the leaf nodes of the binary tree
  38. def print_leaves(root):
  39.     if root is not None:
  40.         print_leaves(root.left)
  41.         if root.left is None and root.right is None:
  42.             print(root.data, end=" ")
  43.         print_leaves(root.right)
  44.  
  45.  
  46. # function to print the boundary traversal of the binary tree
  47. def boundary_traversal(root):
  48.     print_left_boundary(root)
  49.     print_leaves(root)
  50.     print_right_boundary(root)
  51.     return
  52.  
  53.  
  54.  
  55. head = node(1)
  56. head.left = node(2)
  57. head.right = node(3)
  58. head.left.left = node(4)
  59. head.left.right = node(5)
  60. head.right.right = node(6)
  61. head.left.left.right = node(7)
  62. head.right.right.left = node(8)
  63. head.left.left.right.left = node(9)
  64. head.left.left.right.left.left = node(10)
  65. head.right.right.left.right = node(11)
  66. print("Boundary view of the binary tree is : ")
  67. boundary_traversal(head)
Add Comment
Please, Sign In to add comment