Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # https://code2begin.blogspot.com
- # Program to print all paths from root to leaf nodes in a given binary tree
- # node class
- class node:
- def __init__(self, element):
- self.data = element
- self.hd = -1
- self.left = None
- self.right = None
- # function to print the path vector
- def printPath(path):
- for ind in path:
- print(ind, end=" ")
- # function to print all paths from root to leaf using recursive preorder traversal
- def all_paths_from_root_to_leaf(current, path = list()):
- if current is None:
- return
- # push the current node data into the path vector
- path.append(current.data)
- # if the current node is the leaf node then we print the path and return
- if current.left is None and current.right is None:
- printPath(path)
- path.pop()
- print()
- return
- # else we traverse deeper into the binary tree in preorder fashion
- else:
- all_paths_from_root_to_leaf(current.left, path)
- all_paths_from_root_to_leaf(current.right, path)
- path.pop()
- 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)
- head.hd = 0
- print("All the paths from root to the leaf nodes are : ")
- all_paths_from_root_to_leaf(head)
Add Comment
Please, Sign In to add comment