Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # http://code2begin.blogspot.com
- # program to print boundary traversal of a given binary tree
- # node class
- class node:
- def __init__(self, element):
- self.data = element
- self.left = None
- self.right = None
- # function to print the left boundary of the tree
- def print_left_boundary(root):
- if root is not None:
- if root.left is not None:
- print(root.data, end=" ")
- print_left_boundary(root.left)
- elif root.right is not None:
- print(root.data, end=" ")
- print_left_boundary(root.right)
- return
- # function to print the left boundary of the tree
- def print_right_boundary(root):
- if root is not None:
- if root.right is not None:
- print_right_boundary(root.right)
- print(root.data, end=" ")
- elif root.left is not None:
- print_right_boundary(root.left)
- print(root.data, end=" ")
- return
- # function to print the leaf nodes of the binary tree
- def print_leaves(root):
- if root is not None:
- print_leaves(root.left)
- if root.left is None and root.right is None:
- print(root.data, end=" ")
- print_leaves(root.right)
- # function to print the boundary traversal of the binary tree
- def boundary_traversal(root):
- print_left_boundary(root)
- print_leaves(root)
- print_right_boundary(root)
- return
- head = node(1)
- head.left = node(2)
- head.right = node(3)
- head.left.left = node(4)
- head.left.right = node(5)
- head.right.right = node(6)
- head.left.left.right = node(7)
- head.right.right.left = node(8)
- head.left.left.right.left = node(9)
- head.left.left.right.left.left = node(10)
- head.right.right.left.right = node(11)
- print("Boundary view of the binary tree is : ")
- boundary_traversal(head)
Add Comment
Please, Sign In to add comment