Open In App

Find n-th node of inorder traversal

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given a binary tree. The task is to find the n-th node of inorder traversal.

Examples: 

Input:

Find-n-th-node-of-inorder-traversal

Output: 10
Explanation: Inorder Traversal is: 40 20 50 10 30 and value of 4th node is 10.

Input:

Find-n-th-node-of-inorder-traversal-2

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));

Output
10

[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));

Output
10

Next Article
Practice Tags :

Similar Reads