Find n-th node of inorder traversal
Last Updated :
11 Oct, 2024
Given a binary tree. The task is to find the n-th node of inorder traversal.
Examples:
Input:
Output: 10
Explanation: Inorder Traversal is: 40 20 50 10 30 and value of 4th node is 10.
Input:
Output : 8
Explanation: Inorder Traversal is: 2 7 8 3 5 and value of 3rd node is 8.
[Naive Approach] Using In-order traversal - O(n) Time and O(h) Space
The idea is to traverse the binary tree in in-order manner and maintain the count of nodes visited so far. For each node, increment the count. If the count becomes equal to n, then return the value of current node. Otherwise, check left and right subtree of node. If nth node is not found in current tree, then return -1.
Below is the implementation of the above approach.
C++
// C++ program for nth node of inorder traversals
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left, *right;
Node (int x) {
data = x;
left = nullptr;
right = nullptr;
}
};
// Given a binary tree, print its nth inorder node.
int nthInorder(Node* root, int &n) {
// base case
if (root == nullptr) return -1;
int left = nthInorder(root->left, n);
// if nth node is found in left subtree
if (left != -1) return left;
// If curr node is the nth node
if (n == 1)
return root->data;
n--;
int right = nthInorder(root->right, n);
return right;
}
int main() {
// hard coded binary tree.
// 10
// / \
// 20 30
// / \
// 40 50
Node* root = new Node(10);
root->left = new Node(20);
root->right = new Node(30);
root->left->left = new Node(40);
root->left->right = new Node(50);
int n = 4;
cout << nthInorder(root, n) << endl;
return 0;
}
Java
// Java program for nth node of inorder traversals
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// Given a binary tree, print its nth inorder node.
static int nthInorder(Node root, int[] n) {
// base case
if (root == null) return -1;
int left = nthInorder(root.left, n);
// if nth node is found in left subtree
if (left != -1) return left;
// If curr node is the nth node
if (n[0] == 1) {
return root.data;
}
n[0]--;
int right = nthInorder(root.right, n);
return right;
}
public static void main(String[] args) {
// hard coded binary tree.
// 10
// / \
// 20 30
// / \
// 40 50
Node root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(50);
int[] n = {4};
System.out.println(nthInorder(root, n));
}
}
Python
# Python program for nth node of inorder traversals
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# Given a binary tree, print its nth inorder node.
def nthInorder(root, n):
# base case
if root is None:
return -1
left = nthInorder(root.left, n)
# if nth node is found in left subtree
if left != -1:
return left
# If curr node is the nth node
if n[0] == 1:
return root.data
n[0] -= 1
right = nthInorder(root.right, n)
return right
if __name__ == "__main__":
# hard coded binary tree.
# 10
# / \
# 20 30
# / \
# 40 50
root = Node(10)
root.left = Node(20)
root.right = Node(30)
root.left.left = Node(40)
root.left.right = Node(50)
n = [4]
print(nthInorder(root, n))
C#
// C# program for nth node of
// inorder traversals
using System;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// Given a binary tree, print its nth inorder node.
static int nthInorder(Node root, ref int n) {
// base case
if (root == null) return -1;
int left = nthInorder(root.left, ref n);
// if nth node is found in left subtree
if (left != -1) return left;
// If curr node is the nth node
if (n == 1) {
return root.data;
}
n--;
int right = nthInorder(root.right, ref n);
return right;
}
static void Main(string[] args) {
// hard coded binary tree.
// 10
// / \
// 20 30
// / \
// 40 50
Node root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(50);
int n = 4;
Console.WriteLine(nthInorder(root, ref n));
}
}
JavaScript
// JavaScript program for nth node
// of inorder traversals
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// Given a binary tree, print
// its nth inorder node.
function nthInorder(root, n) {
// base case
if (root === null) return -1;
let left = nthInorder(root.left, n);
// if nth node is found in left subtree
if (left !== -1) return left;
// If curr node is the nth node
if (n[0] === 1) {
return root.data;
}
n[0]--;
let right = nthInorder(root.right, n);
return right;
}
// hard coded binary tree.
// 10
// / \
// 20 30
// / \
// 40 50
let root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(50);
let n = [4];
console.log(nthInorder(root, n));
[Expected Approach] Using Morris Traversal Algorithm - O(n) Time and O(1) Space
The idea is to use Morris Traversal Algorithm to perform in-order traversal of the binary tree, while maintaining the count of nodes visited so far.
Below is the implementation of the above approach:
C++
// C++ program for nth node of inorder traversals
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left, *right;
Node (int x) {
data = x;
left = nullptr;
right = nullptr;
}
};
// Given a binary tree, print its nth inorder node.
int nthInorder(Node* root, int n) {
Node* curr = root;
while (curr != nullptr) {
// if left child is null, check
// curr node and move to right node.
if (curr->left == nullptr) {
if (n==1) return curr->data;
n--;
curr = curr->right;
}
else {
// Find the inorder predecessor of curr
Node* pre = curr->left;
while (pre->right != nullptr
&& pre->right != curr)
pre = pre->right;
// Make curr as the right child of its
// inorder predecessor and move to
// left node.
if (pre->right == nullptr) {
pre->right = curr;
curr = curr->left;
}
// Revert the changes made in the 'if' part to
// restore the original tree i.e., fix the right
// child of predecessor
else {
pre->right = nullptr;
if (n == 1) return curr->data;
n--;
curr = curr->right;
}
}
}
// If number of nodes is less than n.
return -1;
}
int main() {
// hard coded binary tree.
// 10
// / \
// 20 30
// / \
// 40 50
Node* root = new Node(10);
root->left = new Node(20);
root->right = new Node(30);
root->left->left = new Node(40);
root->left->right = new Node(50);
int n = 4;
cout << nthInorder(root, n) << endl;
return 0;
}
C
// C program for nth node of inorder traversals
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Given a binary tree, print its nth inorder node.
int nthInorder(struct Node* root, int n) {
struct Node* curr = root;
while (curr != NULL) {
// if left child is null, check
// curr node and move to right node.
if (curr->left == NULL) {
if (n == 1) return curr->data;
n--;
curr = curr->right;
} else {
// Find the inorder predecessor of curr
struct Node* pre = curr->left;
while (pre->right != NULL && pre->right != curr)
pre = pre->right;
// Make curr as the right child of its
// inorder predecessor and move to
// left node.
if (pre->right == NULL) {
pre->right = curr;
curr = curr->left;
}
// Revert the changes made in the 'if' part to
// restore the original tree i.e., fix the right
// child of predecessor
else {
pre->right = NULL;
if (n == 1) return curr->data;
n--;
curr = curr->right;
}
}
}
// If number of nodes is less than n.
return -1;
}
struct Node* createNode(int x) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->data = x;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
int main() {
// hard coded binary tree.
// 10
// / \
// 20 30
// / \
// 40 50
struct Node* root = createNode(10);
root->left = createNode(20);
root->right = createNode(30);
root->left->left = createNode(40);
root->left->right = createNode(50);
int n = 4;
printf("%d\n", nthInorder(root, n));
return 0;
}
Java
// Java program for nth node of inorder traversals
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// Given a binary tree, print its nth inorder node.
static int nthInorder(Node root, int n) {
Node curr = root;
while (curr != null) {
// if left child is null, check
// curr node and move to right node.
if (curr.left == null) {
if (n == 1) return curr.data;
n--;
curr = curr.right;
} else {
// Find the inorder predecessor of curr
Node pre = curr.left;
while (pre.right != null && pre.right != curr)
pre = pre.right;
// Make curr as the right child of its
// inorder predecessor and move to
// left node.
if (pre.right == null) {
pre.right = curr;
curr = curr.left;
}
// Revert the changes made in the 'if' part to
// restore the original tree i.e., fix the right
// child of predecessor
else {
pre.right = null;
if (n == 1) return curr.data;
n--;
curr = curr.right;
}
}
}
// If number of nodes is less than n.
return -1;
}
public static void main(String[] args) {
// hard coded binary tree.
// 10
// / \
// 20 30
// / \
// 40 50
Node root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(50);
int n = 4;
System.out.println(nthInorder(root, n));
}
}
Python
# Python program for nth node of inorder traversals
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# Given a binary tree, print its nth
# inorder node.
def nthInorder(root, n):
curr = root
while curr:
# if left child is null, check
# curr node and move to right node.
if curr.left is None:
if n == 1:
return curr.data
n -= 1
curr = curr.right
else:
# Find the inorder predecessor of curr
pre = curr.left
while pre.right is not None \
and pre.right != curr:
pre = pre.right
# Make curr as the right child of its
# inorder predecessor and move to
# left node.
if pre.right is None:
pre.right = curr
curr = curr.left
else:
pre.right = None
if n == 1:
return curr.data
n -= 1
curr = curr.right
# If number of nodes is less than n.
return -1
if __name__ == "__main__":
# hard coded binary tree.
# 10
# / \
# 20 30
# / \
# 40 50
root = Node(10)
root.left = Node(20)
root.right = Node(30)
root.left.left = Node(40)
root.left.right = Node(50)
n = 4
print(nthInorder(root, n))
C#
// C# program for nth node of inorder
// traversals
using System;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// Given a binary tree, print its nth inorder node.
static int nthInorder(Node root, int n) {
Node curr = root;
while (curr != null) {
// if left child is null, check
// curr node and move to right node.
if (curr.left == null) {
if (n == 1) return curr.data;
n--;
curr = curr.right;
} else {
// Find the inorder predecessor of curr
Node pre = curr.left;
while (pre.right != null && pre.right != curr)
pre = pre.right;
// Make curr as the right child of its
// inorder predecessor and move to
// left node.
if (pre.right == null) {
pre.right = curr;
curr = curr.left;
} else {
pre.right = null;
if (n == 1) return curr.data;
n--;
curr = curr.right;
}
}
}
// If number of nodes is less than n.
return -1;
}
static void Main(string[] args) {
// hard coded binary tree.
// 10
// / \
// 20 30
// / \
// 40 50
Node root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(50);
int n = 4;
Console.WriteLine(nthInorder(root, n));
}
}
JavaScript
// JavaScript program for nth node
// of inorder traversals
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// Given a binary tree, print its
// nth inorder node.
function nthInorder(root, n) {
let curr = root;
while (curr !== null) {
// if left child is null, check
// curr node and move to right node.
if (curr.left === null) {
if (n === 1) return curr.data;
n--;
curr = curr.right;
} else {
// Find the inorder predecessor of curr
let pre = curr.left;
while (pre.right !== null && pre.right !== curr)
pre = pre.right;
// Make curr as the right child of its
// inorder predecessor and move to
// left node.
if (pre.right === null) {
pre.right = curr;
curr = curr.left;
} else {
pre.right = null;
if (n === 1) return curr.data;
n--;
curr = curr.right;
}
}
}
// If number of nodes is less than n.
return -1;
}
// hard coded binary tree.
// 10
// / \
// 20 30
// / \
// 40 50
let root = new Node(10);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(40);
root.left.right = new Node(50);
let n = 4;
console.log(nthInorder(root, n));
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read