VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-n-th-node-inorder-traversal/

⇱ Find n-th node of inorder traversal - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:

👁 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.


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:


Output
10
Comment
Article Tags: