Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Find the kth node in vertical order traversal of a Binary Tree
Next article icon

Find n-th node in Preorder traversal of a Binary Tree

Last Updated : 26 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Examples:  

Input:

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

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

Input:

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

Output : 3
Explanation: Preorder Traversal is: 7 2 3 8 5 and value of 3rd node is 3.

Table of Content

  • [Naive Approach] Using Pre-Order traversal – O(n) Time and O(h) Space
  • [Expected Approach] Using Morris Traversal Algorithm – O(n) Time and O(1) Space

[Naive Approach] Using Pre-Order traversal – O(n) Time and O(h) Space

The idea is to traverse the binary tree in preorder 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 // preorder 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 // preorder node. int nthPreorder(Node* root, int &n) {          // base case     if (root == nullptr) return -1;          // If curr node is the nth node      if (n == 1)          return root->data;     n--;          int left = nthPreorder(root->left, n);          // if nth node is found in left subtree     if (left != -1) return left;          int right = nthPreorder(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 << nthPreorder(root, n) << endl;     return 0; } 
Java
// Java program for  nth node of // preorder 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   	// preorder node.     static int nthPreorder(Node root, int[] n) {          // base case         if (root == null) return -1;          // If curr node is the nth node         if (n[0] == 1)             return root.data;         n[0]--;          int left = nthPreorder(root.left, n);          // if nth node is found in left subtree         if (left != -1) return left;          int right = nthPreorder(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(nthPreorder(root, n));     } } 
Python
# Python program for  nth node of  # preorder traversals  class Node:     def __init__(self, x):         self.data = x         self.left = None         self.right = None  # Given a binary tree, print its nth  # preorder node. def nthPreorder(root, n):      # base case     if root is None:         return -1      # If curr node is the nth node     if n[0] == 1:         return root.data     n[0] -= 1      left = nthPreorder(root.left, n)      # if nth node is found in      # left subtree     if left != -1:         return left      right = nthPreorder(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(nthPreorder(root, n)) 
C#
// C# program for  nth node of // preorder 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   	// preorder node.     static int nthPreorder(Node root, ref int n) {          // base case         if (root == null) return -1;          // If curr node is the nth node         if (n == 1)             return root.data;         n--;          int left = nthPreorder(root.left, ref n);          // if nth node is found in left subtree         if (left != -1) return left;          int right = nthPreorder(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(nthPreorder(root, ref n));     } } 
JavaScript
// JavaScript program for  nth node  // of preorder traversals  class Node {     constructor(x) {         this.data = x;         this.left = null;         this.right = null;     } }  // Given a binary tree, print its  // nth preorder node. function nthPreorder(root, n) {      // base case     if (root === null) return -1;      // If curr node is the nth node     if (n[0] === 1)         return root.data;     n[0]--;      let left = nthPreorder(root.left, n);      // if nth node is found in left subtree     if (left !== -1) return left;      let right = nthPreorder(root.right, n);     return right; }  const 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(nthPreorder(root, n)); 

Output
50 

[Expected Approach] Using Morris Traversal Algorithm – O(n) Time and O(1) Space

The idea is to use Morris Traversal Algorithm to perform pre-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 // preorder 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 // preorder node. int nthPreorder(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, check curr node              // and move to left node.             if (pre->right == nullptr) {                 pre->right = curr;                                  if (n == 1) return curr->data;                 n--;                                  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;                 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 << nthPreorder(root, n) << endl;     return 0; } 
Java
// Java program for  nth node of // preorder 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 preorder node.     static int nthPreorder(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, check curr node                 // and move to left node.                 if (pre.right == null) {                     pre.right = curr;                      if (n == 1) return curr.data;                     n--;                      curr = curr.left;                 } else {                                          // Revert the changes made in the 'if' part to                     // restore the original tree i.e., fix the right                     // child of predecessor.                     pre.right = null;                     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(nthPreorder(root, n));     } } 
Python
# Python program for  nth node of # preorder traversals  class Node:     def __init__(self, x):         self.data = x         self.left = None         self.right = None  # Given a binary tree, print its # nth preorder node. def nthPreorder(root, n):     curr = root     while curr is not None:          # if left child is null, check         # curr node and move to right node.         if curr.left is None:              if n[0] == 1:                 return curr.data             n[0] -= 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, check curr node             # and move to left node.             if pre.right is None:                 pre.right = curr                  if n[0] == 1:                     return curr.data                 n[0] -= 1                  curr = curr.left             else:                                  # Revert the changes made in the 'if' part to                 # restore the original tree i.e., fix the right                 # child of predecessor.                 pre.right = None                 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(nthPreorder(root, n)) 
C#
// C# program for  nth node of // preorder traversals  using System;  public 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 preorder node.     static int nthPreorder(Node root, ref 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, check curr node                 // and move to left node.                 if (pre.right == null) {                     pre.right = curr;                      if (n == 1) return curr.data;                     n--;                      curr = curr.left;                 } else {                                          // Revert the changes made in the 'if' part to                     // restore the original tree i.e., fix the right                     // child of predecessor.                     pre.right = null;                     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(nthPreorder(root, ref n));     } } 
JavaScript
// Javascript program for  nth node of // preorder traversals  class Node {     constructor(x) {         this.data = x;         this.left = null;         this.right = null;     } }  // Given a binary tree, print its nth // preorder node. function nthPreorder(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[0] === 1) return curr.data;             n[0]--;             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, check curr node             // and move to left node.             if (pre.right === null) {                 pre.right = curr;                  if (n[0] === 1) return curr.data;                 n[0]--;                  curr = curr.left;             } else {                                  // Revert the changes made in the 'if' part to                 // restore the original tree i.e., fix the right                 // child of predecessor.                 pre.right = null;                 curr = curr.right;             }         }     }      // If number of nodes     // is less than n.     return -1; }  const 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(nthPreorder(root, n)); 

Output
50 


Next Article
Find the kth node in vertical order traversal of a Binary Tree

A

akash1295
Improve
Article Tags :
  • DSA
  • Tree
  • Binary Tree
  • Preorder Traversal
  • tree-traversal
Practice Tags :
  • Tree

Similar Reads

  • Find the kth node in vertical order traversal of a Binary Tree
    Given a binary tree and an integer k, the task is to return the kth node in the vertical order traversal of a binary tree. If no such node exists then return -1.The vertical order traversal of a binary tree means to print it vertically. Examples: Input: k = 3 Output: 1Explanation: The below image sh
    9 min read
  • Find the parent of a node in the given binary tree
    Given a Binary Tree and a node, the task is to find the parent of the given node in the tree. Return -1 if the given node is the root node.Note: In a binary tree, a parent node of a given node is the node that is directly connected above the given node. Examples: Input: target = 3 Output: 1Explanati
    6 min read
  • Find parent of given node in a Binary Tree with given postorder traversal
    Given two integers N and K where N denotes the height of a binary tree, the task is to find the parent of the node with value K in a binary tree whose postorder traversal is first [Tex]2^{N}-1 [/Tex] natural numbers [Tex](1, 2, ... 2^{N}-1) [/Tex] For N = 3, the Tree will be - 7 / \ 3 6 / \ / \ 1 2
    9 min read
  • Double Order Traversal of a Binary Tree
    Given a Binary Tree, the task is to find its Double Order Traversal. Double Order Traversal is a tree traversal technique in which every node is traversed twice in the following order: Visit the Node.Traverse the Left Subtree.Visit the Node.Traverse the Right Subtree.Examples: Input: Output: 1 7 4 4
    6 min read
  • Middle To Up-Down Order traversal of a Binary Tree
    Given a binary tree, the task is to traverse this binary tree from the middle to the up-down order. In Middle to up-down order traversal, the following steps are performed: First, print the middle level of the tree.Then, print the elements at one level above the middle level of the tree.Then, print
    15+ min read
  • Preorder Traversal of Binary Tree
    Preorder traversal is a tree traversal method that follows the Root-Left-Right order: The root node of the subtree is visited first.Next, the left subtree is recursively traversed.Finally, the right subtree is recursively traversed.How does Preorder Traversal work?Key Properties: Used in expression
    5 min read
  • Flatten binary tree in order of post-order traversal
    Given a binary tree, the task is to flatten it in order of its post-order traversal. In the flattened binary tree, the left node of all the nodes must be NULL. Examples: Input: 5 / \ 3 7 / \ / \ 2 4 6 8 Output: 2 4 3 6 8 7 5 Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 5 4 3 2 1 A simple approach will be to rec
    7 min read
  • Mix Order Traversal of a Binary Tree
    Given a Binary Tree consisting of N nodes, the task is to print its Mix Order Traversal. Mix Order Traversal is a tree traversal technique, which involves any two of the existing traversal techniques like Inorder, Preorder and Postorder Traversal. Any two of them can be performed or alternate levels
    13 min read
  • Preorder Successor of a Node in Binary Tree
    Given a binary tree and a node in the binary tree, find the preorder successor of the given node. It may be assumed that every node has a parent link. Examples: Consider the following binary tree 20 / \ 10 26 / \ / \ 4 18 24 27 / \ 14 19 / \ 13 15 Input : 4 Output : 18 Preorder traversal of given tr
    9 min read
  • Flatten Binary Tree in order of Level Order Traversal
    Given a Binary Tree, the task is to flatten it in order of Level order traversal of the tree. In the flattened binary tree, the left node of all the nodes must be NULL.Examples: Input: 1 / \ 5 2 / \ / \ 6 4 9 3 Output: 1 5 2 6 4 9 3 Input: 1 \ 2 \ 3 \ 4 \ 5 Output: 1 2 3 4 5 Approach: We will solve
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences