m2skills

all paths python

Jun 3rd, 2018
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | None | 0 0
  1. # https://code2begin.blogspot.com
  2. # Program to print all paths from root to leaf nodes in a given binary tree
  3.  
  4. # node class
  5. class node:
  6.     def __init__(self, element):
  7.         self.data = element
  8.         self.hd = -1
  9.         self.left = None
  10.         self.right = None
  11.  
  12.  
  13. # function to print the path vector
  14. def printPath(path):
  15.     for ind in path:
  16.         print(ind, end=" ")
  17.  
  18.  
  19. # function to print all paths from root to leaf using recursive preorder traversal
  20. def all_paths_from_root_to_leaf(current, path = list()):
  21.     if current is None:
  22.         return
  23.  
  24.     # push the current node data into the path vector
  25.     path.append(current.data)
  26.  
  27.     # if the current node is the leaf node then we print the path and return
  28.     if current.left is None and current.right is None:
  29.         printPath(path)
  30.         path.pop()
  31.         print()
  32.         return
  33.  
  34.     # else we traverse deeper into the binary tree in preorder fashion
  35.     else:
  36.         all_paths_from_root_to_leaf(current.left, path)
  37.         all_paths_from_root_to_leaf(current.right, path)
  38.         path.pop()
  39.  
  40.  
  41.  
  42. head = node(1)
  43. head.left = node(2)
  44. head.right = node(3)
  45. head.left.left = node(4)
  46. head.left.right = node(5)
  47. head.right.right = node(6)
  48. head.left.left.right = node(7)
  49. head.right.right.left = node(8)
  50. head.left.left.right.left = node(9)
  51. head.left.left.right.left.left = node(10)
  52. head.right.right.left.right = node(11)
  53. head.hd = 0
  54.  
  55.  
  56. print("All the paths from root to the leaf nodes are : ")
  57. all_paths_from_root_to_leaf(head)
Add Comment
Please, Sign In to add comment