Given a Binary Tree, find the deepest leaf node that is right child of its parent. For example, consider the following tree. The deepest right leaf node is the node with value 10.
Input : 1 / \ 2 3 \ / \ 4 5 6 \ \ 7 8 / \ 9 10 Output : 10
The idea is similar to Method 2 of level order traversal
Traverse the tree level by level and while pushing right child to queue, check if it is leaf node, if it’s leaf node, then update the result and since we are traversing level by level, the last stored right leaf will be the deepest right leaf node.
# Python3 program to find closest
# value in Binary search Tree
_MIN = -2147483648
_MAX = 2147483648
# Helper function that allocates a new
# node with the given data and None
# left and right poers.
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# utility function to return level
# of given node
def getDeepestRightLeafNode(root) :
if (not root):
# create a queue for level
# order traversal
q = 
result = None
# traverse until the queue is empty
temp = q
# Since we go level by level, the last
# stored right leaf node is deepest one
if (not temp.right.left and
result = temp.right
# Driver Code
if __name__ == ‘__main__’:
# create a binary tree
root = newnode(1)
root.left = newnode(2)
root.right = newnode(3)
root.left.right = newnode(4)
root.right.left = newnode(5)
root.right.right = newnode(6)
root.right.left.right = newnode(7)
root.right.right.right = newnode(8)
root.right.left.right.left = newnode(9)
root.right.right.right.right = newnode(10)
result = getDeepestRightLeafNode(root)
print(“Deepest Right Leaf Node ::”,
print(“No result, right leaf not found”)
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
Deepest Right Leaf Node :: 10
Time Complexity : O(n)
- Tree Traversals (Inorder, Preorder and Postorder)
- Find the node with minimum value in a Binary Search Tree
- Write a program to Calculate Size of a tree | Recursion
- Write a Program to Find the Maximum Depth or Height of a Tree
- Write a program to Delete a Tree
- If you are given two traversal sequences, can you construct the binary tree?
- Convert a Binary Tree into its Mirror Tree
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Lowest Common Ancestor in a Binary Search Tree.
- The Great Tree-List Recursion Problem.
- Check sum of Covered and Uncovered nodes of Binary Tree
- Level Order Tree Traversal
- Program to count leaf nodes in a binary tree
- A program to check if a binary tree is BST or not
- Check for Children Sum Property in a Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : SHUBHAMSINGH10