m2skills

deepest leaf python

Jun 13th, 2018
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. # http://code2begin.blogspot.com
  2. # program to find the deepest leaf node in a given 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 deepest leaf node in the binary tree using inorder traversal method
  13. def deepest_level_leaf_node(root):
  14.  
  15.     def deepest_leaf(root, level=0):
  16.         # if the tree is empty or if we reach a leaf node then return 0
  17.         if root is None:
  18.             return -1, -1
  19.  
  20.         # check in the left subtree for the element
  21.         # if found then return the level
  22.         deepest_leaf(root.left, level + 1)
  23.         if root.left is None and root.right is None and deepest_leaf.max_level < level:
  24.             deepest_leaf.max_level = max(deepest_leaf.max_level, level)
  25.             deepest_leaf.answer = root.data
  26.         deepest_leaf(root.right, level + 1)
  27.  
  28.     deepest_leaf.max_level = -1
  29.     deepest_leaf.answer = -1
  30.     deepest_leaf(head, 0)
  31.     return deepest_leaf.max_level, deepest_leaf.answer
  32.  
  33.  
  34. head = node(1)
  35. head.left = node(2)
  36. head.right = node(3)
  37. head.left.left = node(4)
  38. head.left.right = node(5)
  39. head.right.right = node(6)
  40. head.left.left.right = node(7)
  41. head.right.right.left = node(8)
  42. head.left.left.right.left = node(9)
  43. head.left.left.right.left.left = node(10)
  44. head.right.right.left.right = node(11)
  45. temp, answer = deepest_level_leaf_node(head)
  46. print("The deepest leaf node of the binary tree is : " + str(answer))
Add Comment
Please, Sign In to add comment