Given the binary tree and you have to find out the n-th node of inorder traversal.
Input : n = 4 10 / \ 20 30 / \ 40 50 Output : 10 Inorder Traversal is : 40 20 50 10 30 Input : n = 3 7 / \ 2 3 / \ 8 5 Output : 8 Inorder: 2 7 8 3 5 3th node is 8
We do simple Inorder Traversal. While doing the traversal, we keep track of count of nodes visited so far. When count becomes n, we print the node.
Below is the implementation of above approach.
“””Python3 program for nth nodes of
# A Binary Tree Node
# Utility function to create a
# new tree node
# Constructor to create a newNode
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.visited = False
count = 
“”” Given a binary tree, prits nth
nodes of inorder”””
def NthInorder(node, n):
if (node == None):
if (count <= n): """ first recur on left child """ NthInorder(node.left, n) count += 1 # when count = n then prelement if (count == n): print(node.data, end = " ") """ now recur on right child """ NthInorder(node.right, n) # Driver Code if __name__ == '__main__': root = newNode(10) root.left = newNode(20) root.right = newNode(30) root.left.left = newNode(40) root.left.right = newNode(50) n = 4 NthInorder(root, n) # This code is contributed # by SHUBHAMSINGH10 [tabby title="C#"]
Time Complexity: O(n)
- Find all possible binary trees with given Inorder Traversal
- Find the Kth node in the DFS traversal of a given subtree in a Tree
- Find n-th node in Postorder traversal of a Binary Tree
- Find n-th node in Preorder traversal of a Binary Tree
- Find Leftmost and Rightmost node of BST from its given preorder traversal
- Find the kth node in vertical order traversal of a Binary Tree
- Inorder Tree Traversal without Recursion
- Inorder Tree Traversal without recursion and without stack!
- Print Postorder traversal from given Inorder and Preorder traversals
- Construct Special Binary Tree from given Inorder traversal
- Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
- Inorder Successor of a node in Binary Tree
- Replace each node in binary tree with the sum of its inorder predecessor and successor
- Cartesian tree from inorder traversal | Segment Tree
- Kth node in Diagonal Traversal of 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.