Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # http://code2begin.blogspot.com
- # program to find the deepest leaf node in 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 deepest leaf node in the binary tree using inorder traversal method
- def deepest_level_leaf_node(root):
- def deepest_leaf(root, level=0):
- # if the tree is empty or if we reach a leaf node then return 0
- if root is None:
- return -1, -1
- # check in the left subtree for the element
- # if found then return the level
- deepest_leaf(root.left, level + 1)
- if root.left is None and root.right is None and deepest_leaf.max_level < level:
- deepest_leaf.max_level = max(deepest_leaf.max_level, level)
- deepest_leaf.answer = root.data
- deepest_leaf(root.right, level + 1)
- deepest_leaf.max_level = -1
- deepest_leaf.answer = -1
- deepest_leaf(head, 0)
- return deepest_leaf.max_level, deepest_leaf.answer
- 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)
- temp, answer = deepest_level_leaf_node(head)
- print("The deepest leaf node of the binary tree is : " + str(answer))
Add Comment
Please, Sign In to add comment