Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Find Nth Node in the Inorder Traversal of a Tree
Finding the nth node in inorder traversal of a binary tree is a common problem in tree algorithms. Inorder traversal visits nodes in the order: left subtree ? root ? right subtree. This article demonstrates how to find the nth node efficiently using a binary tree class with inorder traversal methods.
Understanding Inorder Traversal
In inorder traversal, nodes are visited in this sequence:
- Traverse the left subtree
- Visit the root node
- Traverse the right subtree
For a binary search tree, inorder traversal gives nodes in sorted order.
Binary Tree Implementation
Here's a complete implementation to find the nth node in inorder traversal ?
class BinaryTree_struct:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None
def set_root(self, key):
self.key = key
def inorder_nth(self, n):
return self.inorder_nth_helper_fun(n, [])
def inorder_nth_helper_fun(self, n, in_ord):
if self.left is not None:
temp = self.left.inorder_nth_helper_fun(n, in_ord)
if temp is not None:
return temp
in_ord.append(self)
if n == len(in_ord):
return self
if self.right is not None:
temp = self.right.inorder_nth_helper_fun(n, in_ord)
if temp is not None:
return temp
def insert_to_left(self, new_node):
self.left = new_node
def insert_to_right(self, new_node):
self.right = new_node
def search_elem(self, key):
if self.key == key:
return self
if self.left is not None:
temp = self.left.search_elem(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search_elem(key)
return temp
return None
# Create a simple example tree
root = BinaryTree_struct(10)
root.insert_to_left(BinaryTree_struct(5))
root.insert_to_right(BinaryTree_struct(15))
root.left.insert_to_left(BinaryTree_struct(3))
root.left.insert_to_right(BinaryTree_struct(7))
# Find 3rd node in inorder traversal
third_node = root.inorder_nth(3)
if third_node:
print(f"3rd node in inorder traversal: {third_node.key}")
else:
print("Index exceeds tree size")
# Find all nodes to see the sequence
def inorder_display(node, result=[]):
if node is not None:
inorder_display(node.left, result)
result.append(node.key)
inorder_display(node.right, result)
return result
nodes = inorder_display(root, [])
print(f"Complete inorder sequence: {nodes}")
3rd node in inorder traversal: 7 Complete inorder sequence: [3, 5, 7, 10, 15]
Interactive Menu System
Here's a more robust interactive version that handles user input ?
btree_instance = None
print('Menu (assumes no duplicate keys)')
print('insert <data> at root')
print('insert <data> left of <data>')
print('insert <data> right of <data>')
print('inorder <position>')
print('quit')
while True:
user_input = input('What would you like to do? ').split()
operation = user_input[0].strip().lower()
if operation == 'insert':
data = int(user_input[1])
new_node = BinaryTree_struct(data)
suboperation = user_input[2].strip().lower()
if suboperation == 'at':
btree_instance = new_node
else:
position = user_input[4].strip().lower()
key = int(position)
ref_node = None
if btree_instance is not None:
ref_node = btree_instance.search_elem(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_to_left(new_node)
elif suboperation == 'right':
ref_node.insert_to_right(new_node)
elif operation == 'inorder':
if btree_instance is not None:
index = int(user_input[1].strip().lower())
node = btree_instance.inorder_nth(index)
if node is not None:
print(f'nth term of inorder traversal: {node.key}')
else:
print('The index exceeds maximum possible index.')
else:
print('The tree is empty...')
elif operation == 'quit':
break
How It Works
The algorithm uses a recursive helper function that:
- Traverses left subtree first and checks if nth node is found
- Visits current node by adding it to the traversal list
- Checks if current position matches the desired nth position
- Continues to right subtree if nth node not yet found
Key Features
| Feature | Description |
|---|---|
| Time Complexity | O(n) in worst case |
| Space Complexity | O(h + n) where h is height |
| Early Termination | Stops when nth node is found |
| Error Handling | Returns None if n exceeds tree size |
Conclusion
This implementation efficiently finds the nth node in inorder traversal by combining recursive traversal with early termination. The helper function maintains a count and returns immediately when the target position is reached, making it more efficient than complete traversal.
