Open In App

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.

[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
Practice Tags :

Similar Reads