Open In App

Find n-th node of inorder traversal

Improve
Improve
Like Article
Like
Save
Share
Report

Given the binary tree and you have to find out the n-th node of inorder traversal.

Examples: 

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 the count of nodes visited so far. When the count becomes n, we print the node.

Algorithm:

Step 1: Start 
Step 2: Initialize a static integer variable count to 0.
Step 3: Define a function name it as newNode which take integer data as input and set initially set left = right = null.
Step 4: Create a static function of void return type name it as NthInorder which takes reference to node and integer value as                input parameterwhich print nth node of inorder.
             a. set base condition that is if node equal to null then return
             b. Check if the count is less than or equal to n. If the count is less than or equal to n, then do the following:
                 1. Call NthInorder(node->left, n) to repeat on the left child.
                 2. Add one to the count.
                 3. Verify that the count equals n, and if it does, call cout node->data endl; to print the data of the current node.
                4. Call NthInorder(node->right, n) to repeat the action on the right child.
Step 5: End
 

Below is the implementation of the above approach.

C++




// C++ program for  nth nodes of  inorder traversals
#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};
 
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct Node* newNode(int data)
{
    struct Node* node
        = (struct Node*)malloc(sizeof(struct Node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
 
    return (node);
}
 
/* Given a binary tree, print its nth nodes of inorder*/
void NthInorder(struct Node* node, int n)
{
    static int count = 0;
    if (node == NULL)
        return;
 
    if (count <= n) {
 
        /* first recur on left child */
        NthInorder(node->left, n);
        count++;
 
        // when count = n then print element
        if (count == n)
            cout << node->data<< endl;
 
        /* now recur on right child */
        NthInorder(node->right, n);
    }
}
 
/* Driver program to test above functions*/
int main()
{
    struct Node* root = newNode(10);
    root->left = newNode(20);
    root->right = newNode(30);
    root->left->left = newNode(40);
    root->left->right = newNode(50);
 
    int n = 4;
 
    NthInorder(root, n);
    return 0;
}
 
// This code is contributed by Abhijeet Kumar(abhijeet19403)


C




// C program for  nth nodes of  inorder traversals
#include <stdio.h>
#include <stdlib.h>
 
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};
 
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct Node* newNode(int data)
{
    struct Node* node =
          (struct Node*)malloc(sizeof(struct Node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
 
    return (node);
}
 
/* Given a binary tree, print its nth nodes of inorder*/
void NthInorder(struct Node* node, int n)
{
    static int count = 0;
    if (node == NULL)
        return;
 
    if (count <= n) {
 
        /* first recur on left child */
        NthInorder(node->left, n);
        count++;
 
        // when count = n then print element
        if (count == n)
            printf("%d ", node->data);
 
        /* now recur on right child */
        NthInorder(node->right, n);
    }
}
 
/* Driver program to test above functions*/
int main()
{
    struct Node* root = newNode(10);
    root->left = newNode(20);
    root->right = newNode(30);
    root->left->left = newNode(40);
    root->left->right = newNode(50);
 
    int n = 4;
 
    NthInorder(root, n);
    return 0;
}


Java




// Java program for  nth nodes of  inorder traversals
import java.io.*;
import java.util. *;
 
class Solution
{
static int count =0
/* A binary tree node has data, pointer to left child
and a pointer to right child */
static class Node {
    int data;
     Node left;
     Node right;
}
   
/* Helper function that allocates a new node with the
given data and null left and right pointers. */
 static Node newNode(int data)
{
     Node node = new Node();
    node.data = data;
    node.left = null;
    node.right = null;
   
    return (node);
}
   
 
/* Given a binary tree, print its nth nodes of inorder*/
static void NthInorder( Node node, int n)
    if (node == null)
        return;
   
    if (count <= n) {
        /* first recur on left child */
        NthInorder(node.left, n);
        count++;
   
        // when count = n then print element
        if (count == n)
            System.out.printf("%d ", node.data);
   
        /* now recur on right child */
        NthInorder(node.right, n);
    }
}
   
/* Driver program to test above functions*/
public static void main(String args[])
{
     Node root = newNode(10);
    root.left = newNode(20);
    root.right = newNode(30);
    root.left.left = newNode(40);
    root.left.right = newNode(50);
   
    int n = 4;
   
    NthInorder(root, n);
}
}
 
// This code is contributed
// by Arnab Kundu


Python3




"""Python3 program for nth node of
   inorder traversal"""
 
# A Binary Tree Node
# Utility function to create a
# new tree node
class newNode:
 
    # Constructor to create a newNode
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
        self.visited = False
 
count = [0]
 
""" Given a binary tree, print the nth
    node of inorder traversal"""
def NthInorder(node, n):
 
    if (node == None):
        return
 
    if (count[0] <= n):
 
        """ first recur on left child """
        NthInorder(node.left, n)
        count[0] += 1
 
        # when count = n then print element
        if (count[0] == 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


C#




// C# program for nth nodes of
// inorder traversals
using System;
 
class GFG
{
public static int count = 0;
 
/* A binary tree node has data, pointer
to left child and a pointer to right child */
public class Node
{
    public int data;
    public Node left;
    public Node right;
}
 
/* Helper function that allocates a
new node with the given data and null
left and right pointers. */
public static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = null;
    node.right = null;
 
    return (node);
}
 
/* Given a binary tree, print its
nth nodes of inorder*/
public static void NthInorder(Node node, int n)
{
    if (node == null)
    {
        return;
    }
 
    if (count <= n)
    {
        /* first recur on left child */
        NthInorder(node.left, n);
        count++;
 
        // when count = n then print element
        if (count == n)
        {
            Console.Write("{0:D} ", node.data);
        }
 
        /* now recur on right child */
        NthInorder(node.right, n);
    }
}
 
// Driver Code
public static void Main(string[] args)
{
    Node root = newNode(10);
    root.left = newNode(20);
    root.right = newNode(30);
    root.left.left = newNode(40);
    root.left.right = newNode(50);
 
    int n = 4;
 
    NthInorder(root, n);
}
}
 
// This code is contributed by Shrikant13


Javascript




<script>
 
// JavaScript program for  nth nodes of  inorder traversals
 
/* A binary tree node has data, pointer to left child
and a pointer to right child */
class Node
{
    constructor(data)
    {
        this.data=data;
        this.left=this.right=null;
    }
}
 
let count =0; 
 
/* Given a binary tree, print its nth nodes of inorder*/
function NthInorder(node,n)
{
    if (node == null)
        return;
     
    if (count <= n) {
        /* first recur on left child */
        NthInorder(node.left, n);
        count++;
     
        // when count = n then print element
        if (count == n)
            document.write(node.data+" ");
     
        /* now recur on right child */
        NthInorder(node.right, n);
    }
}
 
/* Driver program to test above functions*/
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;
 
NthInorder(root, n);
 
 
 
// This code is contributed by avanitrachhadiya2155
 
</script>


Output

10

Time Complexity: O(N), where N is the number of nodes in the given binary tree. We need to traverse the given binary tree to find the nth node of inorder traversal.
Auxiliary Space: O(h), where h is the height of the binary tree. The maximum number of function calls on the call stack at any given point is equal to the height of the tree.



Last Updated : 13 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads