The Wayback Machine - https://web.archive.org/web/20240624044633/https://www.geeksforgeeks.org/find-n-th-node-in-postorder-traversal-of-a-binary-tree/
Open In App

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

Last Updated : 28 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Binary tree and a number N, write a program to find the N-th node in the Postorder traversal of the given Binary tree.

Prerequisite: Tree Traversal

Examples:  

Input : N = 4
              11
            /   \
           21    31
         /   \
        41     51
Output : 31
Explanation: Postorder Traversal of given Binary Tree is 41 51 21 31 11, 
so 4th node will be 31.

Input : N = 5
             25
           /    \
          20    30
        /    \ /   \
      18    22 24   32
Output : 32

The idea to solve this problem is to do postorder traversal of the given binary tree and keep track of the count of nodes visited while traversing the tree and print the current node when the count becomes equal to N.

Below is the implementation of the above approach:  

C++




// C++ program to find n-th node of
// Postorder Traversal of Binary Tree
#include <bits/stdc++.h>
using namespace std;
 
// node of tree
struct Node {
    int data;
    Node *left, *right;
};
 
// function to create a new node
struct Node* createNode(int item)
{
    Node* temp = new Node;
    temp->data = item;
    temp->left = NULL;
    temp->right = NULL;
 
    return temp;
}
 
// function to find the N-th node in the postorder
// traversal of a given binary tree
void NthPostordernode(struct Node* root, int N)
{
    static int flag = 0;
 
    if (root == NULL)
        return;
 
    if (flag <= N) {
 
        // left recursion
        NthPostordernode(root->left, N);
 
        // right recursion
        NthPostordernode(root->right, N);
 
        flag++;
 
        // prints the n-th node of preorder traversal
        if (flag == N)
            cout << root->data;
    }
}
 
// driver code
int main()
{
    struct Node* root = createNode(25);
    root->left = createNode(20);
    root->right = createNode(30);
    root->left->left = createNode(18);
    root->left->right = createNode(22);
    root->right->left = createNode(24);
    root->right->right = createNode(32);
 
    int N = 6;
 
    // prints n-th node found
    NthPostordernode(root, N);
 
    return 0;
}


Java




// Java program to find n-th node of
// Postorder Traversal of Binary Tree
public class NthNodePostOrder {
 
    static int flag = 0;
 
    // function to find the N-th node in the postorder
    // traversal of a given binary tree
    public static void NthPostordernode(Node root, int N)
    {
   
        if (root == null)
            return;
   
        if (flag <= N)
        {  
            // left recursion
            NthPostordernode(root.left, N);
            // right recursion
            NthPostordernode(root.right, N);
            flag++;
            // prints the n-th node of preorder traversal
            if (flag == N)
                System.out.print(root.data);
        }
    }
 
 
    public static void main(String args[]) {
        Node root = new Node(25);
        root.left = new Node(20);
        root.right = new Node(30);
        root.left.left = new Node(18);
        root.left.right = new Node(22);
        root.right.left = new Node(24);
        root.right.right = new Node(32);
   
        int N = 6;
   
        // prints n-th node found
        NthPostordernode(root, N);
    }
}
 
/* A binary tree node structure */
class Node
{
    int data;
    Node left, right;
    Node(int data)
    {
        this.data=data;
    }
};
// This code is contributed by Gaurav Tiwari


Python3




"""Python3 program to find n-th node of
Postorder Traversal of Binary Tree"""
 
# A Binary Tree Node
# Utility function to create a new tree node
class createNode:
 
    # Constructor to create a newNode
    def __init__(self, data):
        self.data= data
        self.left = None
        self.right = None
 
# function to find the N-th node
# in the postorder traversal of
# a given binary tree
flag = [0]
def NthPostordernode(root, N):
 
    if (root == None):
        return
 
    if (flag[0] <= N[0]):
         
        # left recursion
        NthPostordernode(root.left, N)
 
        # right recursion
        NthPostordernode(root.right, N)
 
        flag[0] += 1
 
        # prints the n-th node of
        # preorder traversal
        if (flag[0] == N[0]):
            print(root.data)
                         
# Driver Code
if __name__ == '__main__':
    root = createNode(25)
    root.left = createNode(20)
    root.right = createNode(30)
    root.left.left = createNode(18)
    root.left.right = createNode(22)
    root.right.left = createNode(24)
    root.right.right = createNode(32)
 
    N = [6]
 
    # prints n-th node found
    NthPostordernode(root, N)
 
# This code is contributed by
# SHUBHAMSINGH10


C#




// C# program to find n-th node of
// Postorder Traversal of Binary Tree
using System;
 
public class NthNodePostOrder
{
 
    /* A binary tree node structure */
    public class Node
    {
        public int data;
        public Node left, right;
        public Node(int data)
        {
            this.data=data;
        }
    }
    static int flag = 0;
 
    // function to find the N-th node in the postorder
    // traversal of a given binary tree
    static void NthPostordernode(Node root, int N)
    {
        if (root == null)
            return;
     
        if (flag <= N)
        {
            // left recursion
            NthPostordernode(root.left, N);
             
            // right recursion
            NthPostordernode(root.right, N);
            flag++;
             
            // prints the n-th node of preorder traversal
            if (flag == N)
                Console.Write(root.data);
        }
    }
 
    // Driver code
    public static void Main(String []args)
    {
        Node root = new Node(25);
        root.left = new Node(20);
        root.right = new Node(30);
        root.left.left = new Node(18);
        root.left.right = new Node(22);
        root.right.left = new Node(24);
        root.right.right = new Node(32);
     
        int N = 6;
     
        // prints n-th node found
        NthPostordernode(root, N);
    }
}
 
// This code is contributed by Arnab Kundu


Javascript




<script>
 
// JavaScript program to find n-th node of
// Postorder Traversal of Binary Tree
/* A binary tree node structure */
class Node
{
    constructor(data)
    {
        this.left = null;
        this.right = null;
        this.data = data;
    }
}
 
var flag = 0;
// function to find the N-th node in the postorder
// traversal of a given binary tree
function NthPostordernode(root, N)
{
    if (root == null)
        return;
 
    if (flag <= N)
    {
        // left recursion
        NthPostordernode(root.left, N);
         
        // right recursion
        NthPostordernode(root.right, N);
        flag++;
         
        // prints the n-th node of preorder traversal
        if (flag == N)
            document.write(root.data);
    }
}
 
// Driver code
var root = new Node(25);
root.left = new Node(20);
root.right = new Node(30);
root.left.left = new Node(18);
root.left.right = new Node(22);
root.right.left = new Node(24);
root.right.right = new Node(32);
var N = 6;
// prints n-th node found
NthPostordernode(root, N);
 
</script>


Output

30

Complexity Analysis:

  • Time Complexity: O(n)
    Where n is the number of nodes in the given binary tree. 
  • Auxiliary Space: O(h)
    Where h is the height of the tree. The extra space used is due to the recursion function call stack. In the worst case (if the tree is skewed) this can go upto O(n).

Iterative Approach:

The idea to solve this problem is to do iterative postorder traversal of the given binary tree and keep track of the count of nodes visited while traversing the tree and print the current node when the count becomes equal to N.

Below is the implementation of the above approach:  

C++




// C++  program to find nth node of
// postorder traversal of Binary Tree
#include <bits/stdc++.h>
using namespace std;
 
// structure of Tree node
struct Node {
    int data;
    Node *left, *right;
};
 
// fun to create a new node
Node* createNode(int item)
{
    Node* temp = new Node();
    temp->data = item;
    temp->left = temp->right = NULL;
    return temp;
}
 
// fun to find nth node in the postorder traversal of a
// given binary tree
void Nthpostordernode(Node* root, int N)
{
    // base case
    if (!root)
        return;
 
    int cnt = 0;
 
    stack<Node*> s;
    Node* curr = root;
 
    // do iterative postorder traversal as discussed in this
    // post -
    while (!s.empty() || curr != NULL) {
 
        // push all left nodes into stack
        while (curr) {
            s.push(curr);
            curr = curr->left;
        }
 
        Node* temp = s.top()->right;
        // check if right node exists, if not make curr
        // point to temp as we traverse first left nodes,
        // then right nodes followed by root node
        if (!temp) {
            temp = s.top();
            s.pop();
 
            // do cnt++ and check for the nth node
            cnt++;
            if (cnt == N) {
                cout << temp->data << " ";
                return;
            }
            while (!s.empty() && s.top()->right == temp) {
                temp = s.top();
                s.pop();
                cnt++;
                if (cnt == N) {
                    cout << temp->data << " ";
                    return;
                }
            }
        }
        else
            curr = temp;
    }
}
 
// driver code
int main()
{
    // create a tree
    Node* root = createNode(25);
    root->left = createNode(20);
    root->right = createNode(30);
    root->left->left = createNode(18);
    root->left->right = createNode(22);
    root->right->left = createNode(24);
    root->right->right = createNode(32);
 
    int N = 6;
 
    Nthpostordernode(root, N);
 
    return 0;
}
// This code is contributed by Modem Upendra


Java




// Java program to find nth node of
// postorder traversal of Binary Tree
import java.util.*;
 
// class for Tree node
class Node {
    int data;
    Node left, right;
 
    Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
// class to find nth node in the postorder traversal of a
// given binary tree
class NthPostOrderNode {
    // function to find nth node in the postorder traversal
    // of a given binary tree
    static void findNthPostOrderNode(Node root, int N)
    {
        // base case
        if (root == null) {
            return;
        }
 
        int cnt = 0;
 
        Stack<Node> s = new Stack<Node>();
        Node curr = root;
 
        // do iterative postorder traversal as discussed in
        // this post -
        while (!s.empty() || curr != null) {
            // push all left nodes into stack
            while (curr != null) {
                s.push(curr);
                curr = curr.left;
            }
 
            Node temp = s.peek().right;
            // check if right node exists, if not make curr
            // point to temp as we traverse first left
            // nodes, then right nodes followed by root node
            if (temp == null) {
                temp = s.pop();
 
                // do cnt++ and check for the nth node
                cnt++;
                if (cnt == N) {
                    System.out.print(temp.data + " ");
                    return;
                }
                while (!s.empty()
                       && s.peek().right == temp) {
                    temp = s.pop();
                    cnt++;
                    if (cnt == N) {
                        System.out.print(temp.data + " ");
                        return;
                    }
                }
            }
            else {
                curr = temp;
            }
        }
    }
 
    // driver code
    public static void main(String[] args)
    {
        // create a tree
        Node root = new Node(25);
        root.left = new Node(20);
        root.right = new Node(30);
        root.left.left = new Node(18);
        root.left.right = new Node(22);
        root.right.left = new Node(24);
        root.right.right = new Node(32);
 
        int N = 6;
 
        findNthPostOrderNode(root, N);
    }
}


Python




# python program to find nth node of
# postorder traversal of binary tree
# structure of tree node
class Node:
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
 
# function to create a new node
def createNode(item):
    temp = Node(item)
    return temp
 
 
# function to find the nth node in the postorder traversal
def Nthpostordernode(root, N):
    # base case
    if(root is None):
        return
 
    cnt = 0
    s = []
    curr = root
 
    # do iterative postorder traversal
    while(len(s) > 0 or curr is not None):
        # push all left nodes into stack
        while(curr is not None):
            s.append(curr)
            curr = curr.left
 
        temp = s[len(s) - 1].right
        # check if right node exist, if not make curr
        # point to temp as we traverse first left nodes,
        # then right nodes followed by root node
        if(temp is None):
            temp = s.pop()
 
            # do cnt++ and check for the nth node
            cnt = cnt+1
            if(cnt == N):
                print(temp.data)
                return
            while(len(s) > 0 and s[len(s)-1].right == temp):
                temp = s.pop()
                cnt += 1
                if(cnt == N):
                    print(temp.data)
                    return
 
        else:
            curr = temp
 
 
# driver code
# create tree
root = createNode(25)
root.left = createNode(20)
root.right = createNode(30)
root.left.left = createNode(18)
root.left.right = createNode(22)
root.right.left = createNode(24)
root.right.right = createNode(32)
 
N = 6
Nthpostordernode(root, N)
 
# this code is contributed by Kirti Agarwal


C#




using System;
using System.Collections.Generic;
 
// class for Tree node
class Node
{
  public int data;
  public Node left, right;
 
  public Node(int item)
  {
    data = item;
    left = right = null;
  }
}
 
// class to find nth node in the postorder traversal of a
// given binary tree
class NthPostOrderNode
{
  // function to find nth node in the postorder traversal
  // of a given binary tree
  static void FindNthPostOrderNode(Node root, int N)
  {
    // base case
    if (root == null)
    {
      return;
    }
 
    int cnt = 0;
 
    Stack<Node> s = new Stack<Node>();
    Node curr = root;
 
    // do iterative postorder traversal as discussed in
    // this post -
    while (s.Count > 0 || curr != null)
    {
      // push all left nodes into stack
      while (curr != null)
      {
        s.Push(curr);
        curr = curr.left;
      }
 
      Node temp = s.Peek().right;
      // check if right node exists, if not make curr
      // point to temp as we traverse first left
      // nodes, then right nodes followed by root node
      if (temp == null)
      {
        temp = s.Pop();
 
        // do cnt++ and check for the nth node
        cnt++;
        if (cnt == N)
        {
          Console.Write(temp.data + " ");
          return;
        }
        while (s.Count > 0 && s.Peek().right == temp)
        {
          temp = s.Pop();
          cnt++;
          if (cnt == N)
          {
            Console.Write(temp.data + " ");
            return;
          }
        }
      }
      else
      {
        curr = temp;
      }
    }
  }
 
  // driver code
  public static void Main()
  {
    // create a tree
    Node root = new Node(25);
    root.left = new Node(20);
    root.right = new Node(30);
    root.left.left = new Node(18);
    root.left.right = new Node(22);
    root.right.left = new Node(24);
    root.right.right = new Node(32);
 
    int N = 6;
 
    FindNthPostOrderNode(root, N);
  }
}


Javascript




// JavaScript program to find the nth node of
// postorder traversal of binary tree
 
// structure of tree node
class Node{
    constructor(item){
        this.data = item;
        this.left = null;
        this.right = null;
    }
}
 
// function to create a new node
function createNode(item){
    return new Node(item);
}
 
// function to find nth node in the postorder
// traversal of a given binary tree
function Nthpostordernode(root, N){
    // base cas
    if(root == null)
        return;
     
    let cnt = 0;
     
    let s = [];
    let curr = root;
     
    // do iterative postorder traversal
    while(s.length > 0 || curr != null){
        // push all left nodes into stack
        while(curr != null){
            s.push(curr);
            curr = curr.left;
        }
         
        let temp = s[s.length - 1].right;
        // check if right node exists, if not make curr
        // point to temp as we traverse first left nodes,
        // then right nodes followed by root node
        if(temp == null){
            temp = s.pop();
             
            // do cnt++ and check for the nth node
            cnt++;
            if(cnt == N){
                document.write(temp.data + " ") ;
                return;
            }
            while(s.length > 0 && s[s.length-1].right == temp){
                temp = s.pop();
                cnt++;
                if(cnt == N){
                    document.write(temp.data + " ");
                    return;
                }
            }
        }
        else{
            curr = temp;
        }
    }
}
 
// driver code
let root = createNode(25);
root.left = createNode(20);
root.right = createNode(30);
root.left.left = createNode(18);
root.left.right = createNode(22);
root.right.left = createNode(24);
root.right.right = createNode(32);
 
let N = 6;
 
Nthpostordernode(root, N);
 
// This code is contributed by Yash Agarwal(yashagarwal2852002)


Output

30 

Complexity Analysis:

  • Time Complexity: O(n)
    Where n is the number of nodes in the given binary tree. 
  • Auxiliary Space: O(h)
    Where h is the height of the tree. The extra space used is due to the recursion function call stack. In the worst case (if the tree is skewed) this can go upto O(n).


Similar Reads

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 4 5 Examples: Input: N = 4, K = 5 Output: 6 Explan
9 min read
Find postorder traversal of BST from preorder traversal
Given an array representing preorder traversal of BST, print its postorder traversal. Examples: Input : 40 30 35 80 100 Output : 35 30 100 80 40 Input : 40 30 32 35 80 90 100 120 Output : 35 32 30 120 100 90 80 40 Prerequisite: Construct BST from given preorder traversal Simple Approach: A simple solution is to first construct BST from a given preo
9 min read
Postorder traversal of Binary Tree without recursion and without stack
Given a binary tree, perform postorder traversal. Prerequisite - Inorder/preorder/postorder traversal of tree We have discussed the below methods for postorder traversal. 1) Recursive Postorder Traversal. 2) Postorder traversal using Stack. 2) Postorder traversal using two Stacks. Approach 1 The approach used is based on using an unordered set to k
15 min read
Preorder, Postorder and Inorder Traversal of a Binary Tree using a single Stack
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order iteratively using only one stack traversal. Examples: Input: Output:Preorder Traversal: 1 2 3Inorder Traversal: 2 1 3Postorder Traversal: 2 3 1 Input: Output:Preorder traversal: 1 2 4 5 3 6 7Inorder traversal: 4 2 5 1 6 3 7Post-order tr
13 min read
Postorder Traversal of Binary Tree
Postorder traversal is defined as a type of tree traversal which follows the Left-Right-Root policy such that for each node: The left subtree is traversed firstThen the right subtree is traversedFinally, the root node of the subtree is traversed Algorithm for Postorder Traversal of Binary Tree: The algorithm for postorder traversal is shown as foll
6 min read
Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, we need to write a program to construct the binary tree using these two Preorder traversals.A Full Binary Tree is a binary tree where every node has either 0 or 2 children. Note: It is not possible to construct a general binary tree using these two traver
12 min read
Construct a Complete N-ary Tree from given Postorder Traversal
Given an array arr[] of size M that contains the post-order traversal of a complete N-ary tree, the task is to generate the N-ary tree and print its preorder traversal. A complete tree is a tree where all the levels of the tree are completely filled, except may be for the last level but the nodes in the last level are as left as possible. Examples:
13 min read
Iterative Postorder Traversal of N-ary Tree
Given an N-ary tree, the task is to find the post-order traversal of the given tree iteratively.Examples: Input: 1 / | \ 3 2 4 / \ 5 6 Output: [5, 6, 3, 2, 4, 1] Input: 1 / \ 2 3 Output: [2, 3, 1] Approach:We have already discussed iterative post-order traversal of binary tree using one stack. We will extend that approach for the n-ary tree. The id
10 min read
Postorder successor of a Node in Binary Tree
Given a binary tree and a node in the binary tree, find Postorder successor of the given node. Examples: Consider the following binary tree 20 / \ 10 26 / \ / \ 4 18 24 27 / \ 14 19 / \ 13 15 Postorder traversal of given tree is 4, 13, 15, 14, 19, 18, 10, 24, 27, 26, 20. Input : Complexity Analysis:24 Output : 27 Input : 4 Output : 13 A simple solu
8 min read
Postorder predecessor of a Node in Binary Search Tree
Given a binary tree and a node in the binary tree, find the Postorder predecessor of the given node. Examples: Consider the following binary tree 20 / \ 10 26 / \ / \ 4 18 24 27 / \ 14 19 / \ 13 15 Input : 4 Output : 10 Postorder traversal of given tree is 4, 13, 15, 14, 19, 18, 10, 24, 27, 26, 20. Input : 24 Output : 10 A simple solution is to fir
8 min read
three90RightbarBannerImg