The Wayback Machine - https://web.archive.org/web/20241010175030/https://www.geeksforgeeks.org/inorder-successor-in-binary-search-tree/
Open In App

Inorder Successor in Binary Search Tree

Last Updated : 10 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Binary Tree, Inorder successor of a node is the next node in Inorder traversal of the Binary Tree. Inorder Successor is NULL for the last node in Inorder traversal. 

In the below diagram, inorder successor of 8 is 10, inorder successor of 10 is 12 and inorder successor of 14 is 20.


Using the Standard Binary Tree Inorder Successor Methods:

We have discussed different methods for Inorder successor in a Binary Tree. These methods either work in O(n) time or expect parent pointer / reference to be present in every node. We can use Binary Search Tree properties to efficiently find the successor in O(h) time.

Using Binary Search Tree Properties:

Parent pointer is NOT needed in this algorithm. We follow the idea of normal BST Search. In BST search, we get closer to the key by comparing with the current node. So the last greater key visited during search is the success. The following cases arise during the search.

  • If we reach null, then the given target does not exist, we return null
  • If current node matches the target and right child is not empty, then successor is leftmost node in right subtree.
  • If current node is greater, then it is a potential successor, we mark it as successor and proceed to left
  • If current node is smaller, we proceed to right.
C++
#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* left;
    Node* right;
    Node(int x) {
      data = x;  
      left = right = nullptr; 
    }
};

// Function to find leftmost node in
// subtree with given root.
Node* leftMost(Node* node);

Node* getSucc(Node* root, int target) {
    
    // Base Case 1 :  No Inorder
    if (root == nullptr)
        return nullptr;
     
    // Base Case 2 : root is same as target and 
    // Right child is not empty
    if ( root->data == target && root->right != nullptr)
        return leftMost(root->right);

    // Use BST properties to search for target and
    // successor
    Node* succ = nullptr;
    Node* curr = root; 
    while (curr != nullptr) {
      
        // If curr node is greater, then it
        // is a potential successor
        if (target < curr->data) {
            succ = curr;
            curr = curr->left;
        }
      
        // If smaller, then successor must
        // be in the right chikd
        else if (target > curr->data) 
            curr = curr->right;
      
        // If same then the last visited
        // greater value is successor
        else 
            break;
    }

    return succ;
}

Node* leftMost(Node* node) {
    Node* curr = node;
    while (curr->left != nullptr) 
        curr = curr->left;
    return curr;
}

int main() {
  
    // Construct a  BST
    Node *root = new Node(20);
    root->left = new Node(8);
    root->right = new Node(22);
    root->left->left = new Node(4);
    root->left->right = new Node(12);
    root->left->right->left = new Node(10);
    root->left->right->right = new Node(14);

    int target = 4;
    Node* succ = getSucc(root, target);
    if (succ != nullptr)
        cout << succ->data;
    else
        cout << "null";
    return 0;
}
C
// C program for above approach
#include <stdio.h>
#include <stdlib.h>

/* A binary tree node has data, 
   the pointer to left child
   and a pointer to right child */
struct node 
{
    int data;
    struct node* left;
    struct node* right;
    struct node* parent;
};

struct node* minValue(struct node* node);

struct node* inOrderSuccessor(
    struct node* root,
    struct node* n)
{
    
    // step 1 of the above algorithm
    if (n->right != NULL)
        return minValue(n->right);

    struct node* succ = NULL;

    // Start from root and search for
    // successor down the tree
    while (root != NULL) 
    {
        if (n->data < root->data) 
        {
            succ = root;
            root = root->left;
        }
        else if (n->data > root->data)
            root = root->right;
        else
            break;
    }

    return succ;
}

/* Given a non-empty binary search tree, 
    return the minimum data  
    value found in that tree. Note that 
    the entire tree does not need
    to be searched. */
struct node* minValue(struct node* node)
{
    struct node* current = node;

    /* loop down to find the leftmost leaf */
    while (current->left != NULL) 
    {
        current = current->left;
    }
    return current;
}

/* Helper function that allocates a new 
    node with the given data and 
    NULL left and right pointers. */
struct node* newNode(int data)
{
    struct node* node = (struct node*)
        malloc(sizeof(
            struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    node->parent = NULL;

    return (node);
}

/* Give a binary search tree and 
   a number, inserts a new node with    
    the given number in the correct 
    place in the tree. Returns the new
    root pointer which the caller should
    then use (the standard trick to 
    avoid using reference parameters). */
struct node* insert(struct node* node,
                    int data)
{
    /* 1. If the tree is empty, return a new,
      single node */
    if (node == NULL)
        return (newNode(data));
    else 
    {
        struct node* temp;

        /* 2. Otherwise, recur down the tree */
        if (data <= node->data) 
        {
            temp = insert(node->left, data);
            node->left = temp;
            temp->parent = node;
        }
        else 
        {
            temp = insert(node->right, data);
            node->right = temp;
            temp->parent = node;
        }

        /* return the (unchanged) node pointer */
        return node;
    }
}

/* Driver program to test above functions*/
int main()
{
    struct node *root = NULL, *temp, *succ, *min;

    // creating the tree given in the above diagram
    root = insert(root, 20);
    root = insert(root, 8);
    root = insert(root, 22);
    root = insert(root, 4);
    root = insert(root, 12);
    root = insert(root, 10);
    root = insert(root, 14);
    temp = root->left->right->right;
    
    // Function Call
    succ = inOrderSuccessor(root, temp);
    if (succ != NULL)
        printf(
            "\n Inorder Successor of %d is %d ",
            temp->data, succ->data);
    else
        printf("\n Inorder Successor doesn't exit");

    getchar();
    return 0;
}

// Thanks to R.Srinivasan for suggesting this method.
Java
// Java program for above approach
class GFG
{
  
/* A binary tree node has data, 
   the pointer to left child
   and a pointer to right child */
static class node 
{
    int data;
    node left;
    node right;
    node parent;
};

static node inOrderSuccessor(
    node root,
    node n)
{
    
    // step 1 of the above algorithm
    if (n.right != null)
        return minValue(n.right);

    node succ = null;

    // Start from root and search for
    // successor down the tree
    while (root != null) 
    {
        if (n.data < root.data) 
        {
            succ = root;
            root = root.left;
        }
        else if (n.data > root.data)
            root = root.right;
        else
            break;
    }
    return succ;
}

/* Given a non-empty binary search tree, 
    return the minimum data  
    value found in that tree. Note that 
    the entire tree does not need
    to be searched. */
static node minValue(node node)
{
    node current = node;

    /* loop down to find the leftmost leaf */
    while (current.left != null) 
    {
        current = current.left;
    }
    return current;
}

/* Helper function that allocates a new 
    node with the given data and 
    null left and right pointers. */
static node newNode(int data)
{
    node node = new node();
    node.data = data;
    node.left = null;
    node.right = null;
    node.parent = null;

    return (node);
}

/* Give a binary search tree and 
   a number, inserts a new node with    
    the given number in the correct 
    place in the tree. Returns the new
    root pointer which the caller should
    then use (the standard trick to 
    astatic void using reference parameters). */
static  node insert(node node,
                    int data)
{
  
    /* 1. If the tree is empty, return a new,
      single node */
    if (node == null)
        return (newNode(data));
    else 
    {
        node temp;

        /* 2. Otherwise, recur down the tree */
        if (data <= node.data) 
        {
            temp = insert(node.left, data);
            node.left = temp;
            temp.parent = node;
        }
        else 
        {
            temp = insert(node.right, data);
            node.right = temp;
            temp.parent = node;
        }

        /* return the (unchanged) node pointer */
        return node;
    }
}

/* Driver program to test above functions*/
public static void main(String[] args)
{
    node root = null, temp, succ, min;

    // creating the tree given in the above diagram
    root = insert(root, 20);
    root = insert(root, 8);
    root = insert(root, 22);
    root = insert(root, 4);
    root = insert(root, 12);
    root = insert(root, 10);
    root = insert(root, 14);
    temp = root.left.right.right;
    
    // Function Call
    succ = inOrderSuccessor(root, temp);
    if (succ != null)
        System.out.printf(
            "\n Inorder Successor of %d is %d ",
            temp.data, succ.data);
    else
        System.out.printf("\n Inorder Successor doesn't exit");
}
}

// This code is contributed by gauravrajput1
Python
# Python program to find 
# the inorder successor in a BST

# A binary tree node 
class Node:

    # Constructor to create a new node
    def __init__(self, key):
        self.data = key 
        self.left = None
        self.right = None

def inOrderSuccessor(root, n):
    
    # Step 1 of the above algorithm
    if n.right is not None:
        return minValue(n.right)

    # Step 2 of the above algorithm
    succ=Node(None)
    
    
    while( root):
        if(root.data<n.data):
            root=root.right
        elif(root.data>n.data):
            succ=root
            root=root.left
        else:
            break
    return succ

# Given a non-empty binary search tree, 
# return the minimum data value
# found in that tree. Note that the
# entire tree doesn't need to be searched
def minValue(node):
    current = node

    # loop down to find the leftmost leaf
    while(current is not None):
        if current.left is None:
            break
        current = current.left

    return current


# Given a binary search tree 
# and a number, inserts a
# new node with the given 
# number in the correct place
# in the tree. Returns the 
# new root pointer which the
# caller should then use
# (the standard trick to avoid 
# using reference parameters)
def insert( node, data):

    # 1) If tree is empty 
    # then return a new singly node
    if node is None:
        return Node(data)
    else:
       
        # 2) Otherwise, recur down the tree
        if data <= node.data:
            temp = insert(node.left, data)
            node.left = temp 
            temp.parent = node
        else:
            temp = insert(node.right, data)
            node.right = temp 
            temp.parent = node
        
        # return  the unchanged node pointer
        return node


# Driver program to test above function
if __name__ == "__main__":
  root = None

  # Creating the tree given in the above diagram 
  root = insert(root, 20)
  root = insert(root, 8);
  root = insert(root, 22);
  root = insert(root, 4);
  root = insert(root, 12);
  root = insert(root, 10);  
  root = insert(root, 14);    
  temp = root.left.right 

  succ = inOrderSuccessor( root, temp)
  if succ is not None:
      print("Inorder Successor of" ,
               temp.data ,"is" ,succ.data)
  else:
      print("InInorder Successor doesn't exist")
C#
// C# program for above approach
using System;

public class GFG
{

  /* A binary tree node has data, 
   the pointer to left child
   and a pointer to right child */
  public
    class node 
    {
      public
        int data;
      public
        node left;
      public
        node right;
      public
        node parent;
    };

  static node inOrderSuccessor(
    node root,
    node n)
  {

    // step 1 of the above algorithm
    if (n.right != null)
      return minValue(n.right);

    node succ = null;

    // Start from root and search for
    // successor down the tree
    while (root != null) 
    {
      if (n.data < root.data) 
      {
        succ = root;
        root = root.left;
      }
      else if (n.data > root.data)
        root = root.right;
      else
        break;
    }
    return succ;
  }

  /* Given a non-empty binary search tree, 
    return the minimum data  
    value found in that tree. Note that 
    the entire tree does not need
    to be searched. */
  static node minValue(node node)
  {
    node current = node;

    /* loop down to find the leftmost leaf */
    while (current.left != null) 
    {
      current = current.left;
    }
    return current;
  }

  /* Helper function that allocates a new 
    node with the given data and 
    null left and right pointers. */
  static node newNode(int data)
  {
    node node = new node();
    node.data = data;
    node.left = null;
    node.right = null;
    node.parent = null;

    return (node);
  }

  /* Give a binary search tree and 
   a number, inserts a new node with    
    the given number in the correct 
    place in the tree. Returns the new
    root pointer which the caller should
    then use (the standard trick to 
    astatic void using reference parameters). */
  static  node insert(node node,
                      int data)
  {

    /* 1. If the tree is empty, return a new,
      single node */
    if (node == null)
      return (newNode(data));
    else 
    {
      node temp;

      /* 2. Otherwise, recur down the tree */
      if (data <= node.data) 
      {
        temp = insert(node.left, data);
        node.left = temp;
        temp.parent = node;
      }
      else 
      {
        temp = insert(node.right, data);
        node.right = temp;
        temp.parent = node;
      }

      /* return the (unchanged) node pointer */
      return node;
    }
  }

  /* Driver program to test above functions*/
  public static void Main(String[] args)
  {
    node root = null, temp, succ;

    // creating the tree given in the above diagram
    root = insert(root, 20);
    root = insert(root, 8);
    root = insert(root, 22);
    root = insert(root, 4);
    root = insert(root, 12);
    root = insert(root, 10);
    root = insert(root, 14);
    temp = root.left.right.right;

    // Function Call
    succ = inOrderSuccessor(root, temp);
    if (succ != null)
      Console.Write(
      "\n Inorder Successor of {0} is {1} ",
      temp.data, succ.data);
    else
      Console.Write("\n Inorder Successor doesn't exit");
  }
}

// This code is contributed by gauravrajput1 
JavaScript
<script>

class Node
{
    constructor(data)
    {
        this.data=data;;
        this.left=this.right=this.parent=null;
    }
}

function inOrderSuccessor(root,n)
{
    // step 1 of the above algorithm
    if (n.right != null)
        return minValue(n.right);
 
    let succ = null;
 
    // Start from root and search for
    // successor down the tree
    while (root != null)
    {
        if (n.data < root.data)
        {
            succ = root;
            root = root.left;
        }
        else if (n.data > root.data)
            root = root.right;
        else
            break;
    }
    return succ;
}

function minValue(node)
{
    let current = node;
 
    /* loop down to find the leftmost leaf */
    while (current.left != null)
    {
        current = current.left;
    }
    return current;
}


function insert(node,data)
{
    /* 1. If the tree is empty, return a new,
      single node */
    if (node == null)
        return (new Node(data));
    else
    {
        let temp;
 
        /* 2. Otherwise, recur down the tree */
        if (data <= node.data)
        {
            temp = insert(node.left, data);
            node.left = temp;
            temp.parent = node;
        }
        else
        {
            temp = insert(node.right, data);
            node.right = temp;
            temp.parent = node;
        }
 
        /* return the (unchanged) node pointer */
        return node;
    }
}

let root = null, temp, succ, min;
 
// creating the tree given in the above diagram
root = insert(root, 20);
root = insert(root, 8);
root = insert(root, 22);
root = insert(root, 4);
root = insert(root, 12);
root = insert(root, 10);
root = insert(root, 14);
temp = root.left.right.right;

// Function Call
succ = inOrderSuccessor(root, temp);
if (succ != null)
    document.write(
"<br> Inorder Successor of "+temp.data+"  is "+
 succ.data);
else
    document.write("<br> Inorder Successor doesn't exit");

// This code is contributed by unknown2108

</script>

Output
 Inorder Successor of 14 is 20

Time Complexity: O(h), where h is the height of the tree. 

Auxiliary Space: O(1)




Previous Article
Next Article

Similar Reads

Replace each node in binary tree with the sum of its inorder predecessor and successor
Given a binary tree containing n nodes. The problem is to replace each node in the binary tree with the sum of its inorder predecessor and inorder successor. Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 11 / \ 9 13 / \ / \ 2 3 4 3 For 1: Inorder predecessor = 5 Inorder successor = 6 Sum = 11 For 4: Inorder predecessor = 0 (as inorder predec
15+ min read
Inorder predecessor and successor for a given key in BST | Iterative Approach
Given a BST and a key. The task is to find the inorder successor and predecessor of the given key. In case, if either of predecessor or successor is not present, then print -1.Examples: Input: 50 / \ / \ 30 70 / \ / \ / \ / \ 20 40 60 80 key = 65 Output: Predecessor : 60 Successor : 70 Input: 50 / \ / \ 30 70 / \ / \ / \ / \ 20 40 60 80 key = 100 O
12 min read
Populate Inorder Successor for all nodes
Given a Binary Tree where each node has the following structure, write a function to populate the next pointer for all nodes. The next pointer for every node should be set to point to in-order successor. C/C++ Code class node { public: int data; node* left; node* right; node* next; }; // This code is contributed // by Shubham Singh C/C++ Code struc
8 min read
Inorder predecessor and successor in BST
Given a BST and a key, we need to find the inorder successor and predecessor of the given key. In case the given key is not found in BST, then return the two values within which this key will lie. In the below diagram, successor of 2 is 5 and predecessor is 4. For 1, successor is 3 and predecessor is 5. Using Inorder Traversal:The ida is based on t
12 min read
Pre-Order Successor of all nodes in Binary Search Tree
Consider a BST(Binary Search Tree) where duplicates are not allowed.Given a key present in the BST. The task is to find its pre-order successor in this BST i.e. the task is to find a key that comes next to the given key if we apply a pre-order traversal on given BST. Example: Insert the following keys in a BST in the same order: 51, 39, 31, 54, 92,
15+ min read
Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree.  Input:  Output: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 100 Input:  Output: Inorder Traversal: 8 12 20 22 25 30 40Preorder Tr
11 min read
Check if an array represents Inorder of Binary Search tree or not
Given an array of n elements. The task is to check if it is an Inorder traversal of any Binary Search Tree or not. Examples: Input: arr[] = { 19, 23, 25, 30, 45 }Output: YesExplanation: As the array is sorted in non-decreasing order, it is an Inorder traversal of any Binary Search Tree. Input : arr[] = { 19, 23, 30, 25, 45 }Output : NoExplanation:
4 min read
Check if given inorder and preorder traversals are valid for any Binary Tree without building the tree
cGiven two arrays pre[] and in[] representing the preorder and inorder traversal of the binary tree, the task is to check if the given traversals are valid for any binary tree or not without building the tree. If it is possible, then print Yes. Otherwise, print No. Examples: Input: pre[] = {1, 2, 4, 5, 7, 3, 6, 8}, in[] = {4, 2, 5, 7, 1, 6, 8, 3}Ou
15+ 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
Level Order Successor of a node in Binary Tree
Given a binary tree and a node in the binary tree, find Levelorder successor of the given node. That is, the node that appears after the given node in the level order traversal of the tree. Note: The task is not just to print the data of the node, you have to return the complete node from the tree. Examples: Consider the following binary tree 20 /
9 min read
Modify Binary Tree by replacing each node with the sum of its Preorder Predecessor and Successor
Given a binary tree consisting of N nodes, the task is to replace each node in the binary tree with the sum of its preorder predecessor and preorder successor. Examples: Input: 2 / \ 3 4 / \ / \ 6 5 7 8 Output: 3 / \ 8 12 / \ / \ 8 10 12 7 Explanation: For Node 2: Preorder predecessor = 0 (as preorder predecessor is not present), preorder successor
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 tree is 20, 10, 4, 18, 14, 13, 15, 19, 26, 24, 27. I
9 min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Binary Search Tree vs Ternary Search Tree
For effective searching, insertion, and deletion of items, two types of search trees are used: the binary search tree (BST) and the ternary search tree (TST). Although the two trees share a similar structure, they differ in some significant ways. FeatureBinary Search Tree (BST)Ternary Search Tree (TST)NodeHere, each node has at most two children. H
3 min read
Cartesian tree from inorder traversal | Segment Tree
Given an in-order traversal of a cartesian tree, the task is to build the entire tree from it. Examples: Input: arr[] = {1, 5, 3} Output: 1 5 3 5 / \ 1 3 Input: arr[] = {3, 7, 4, 8} Output: 3 7 4 8 8 / 7 / \ 3 4 Approach: We have already seen an algorithm here that takes O(NlogN) time on an average but can get to O(N2) in the worst case.In this art
13 min read
Van Emde Boas Tree - Set 3 | Successor and Predecessor
It is highly recommended to read the previous articles on Van Emde Boas Tree first. Procedure for successor: Base case: If the size of the tree is 2 then if query-key is 0 and key - 1 is present in the tree then return 1, as it will be the successor. Otherwise, return null.If the key is less than minimum then we can easily say that minimum will be
15+ min read
Proto Van Emde Boas Tree | Set 6 | Query : Successor and Predecessor
Please refer all previous articles on Proto Van Emde Boas Tree first.Successor Query Procedure: Base case: For Proto-VEB of size 2 the only possibility is that key is 0 and if the next key is present then it is its successor or there is no successor. So the same procedure is applied.Recursion: First, we will look in the present cluster (means the c
15+ min read
Construct Special Binary Tree from given Inorder traversal
Given Inorder Traversal of a Special Binary Tree in which the key of every node is greater than keys in left and right children, construct the Binary Tree and return root. Examples: Input: inorder[] = {5, 10, 40, 30, 28} Output: root of following tree 40 / \ 10 30 / \ 5 28 Input: inorder[] = {1, 5, 10, 40, 30, 15, 28, 20} Output: root of following
14 min read
Calculate height of Binary Tree using Inorder and Level Order Traversal
Given inorder traversal and Level Order traversal of a Binary Tree. The task is to calculate the height of the tree without constructing it. Example: Input : Input: Two arrays that represent Inorder and level order traversals of a Binary Tree in[] = {4, 8, 10, 12, 14, 20, 22}; level[] = {20, 8, 22, 4, 12, 10, 14}; Output : 4 The binary tree that ca
12 min read
Print K inorder successors of a Binary Tree in O(1) space
Given a Binary Tree and two numbers P and K, the task is to print the K Inorder Successor of the given number P from the Binary tree in constant space.Examples: Input: Tree: 1 / \ 12 11 / / \ 3 4 13 \ / 15 9 P = 12, K = 4 Output: 1 4 15 11 Explanation: Inorder traversal: 3 12 1 4 15 11 9 13 The 4 Inorder Successor of a node 12 are {1, 4, 15, 11} In
10 min read
Check if Inorder traversal of a Binary Tree is palindrome or not
Given a binary tree and the task if to check if its Inorder Sequence is a palindrome or not. Examples: Input: Output: True Explanation: The Inorder sequence of the tree is "bbaaabb" which is a palindromic string.Input: Output: False Explanation: The Inorder sequence of the tree is "bbdaabb" which is not a palindromic string. Approach: To solve the
8 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
Binary Tree Iterator for Inorder Traversal
Given a Binary Tree and an input array. The task is to create an Iterator that utilizes next() and hasNext() functions to perform Inorder traversal on the binary tree. Examples: Input: 8 Input Array = [next(), hasNext(), next(), next(), next(), hasNext(), next(), next(), hasNext()] / \ 3 9 / \ 2 4 \ 5 Output: [2, true, 3, 4, 5, true, 8, 9, false] E
13 min read
Inorder Non-threaded Binary Tree Traversal without Recursion or Stack
We have discussed Thread based Morris Traversal. Can we do inorder traversal without threads if we have parent pointers available to us? Input: Root of Below Tree [Every node of tree has parent pointer also] 10 / \ 5 100 / \ 80 120 Output: 5 10 80 100 120 The code should not extra space (No Recursion and stack) In inorder traversal, we follow "left
11 min read
Construct a Binary Tree from Postorder and Inorder
Given Postorder and Inorder traversals, construct the tree. Examples: Input: in[] = {2, 1, 3}post[] = {2, 3, 1} Output: Root of below tree 1 / \ 2 3 Input: in[] = {4, 8, 2, 5, 1, 6, 3, 7}post[] = {8, 4, 5, 2, 6, 7, 3, 1} Output: Root of below tree 1 / \ 2 3 / \ / \4 5 6 7 \ 8 Recommended PracticeTree from Postorder and InorderTry It! Approach: To s
15+ min read
Inorder Successo in Binary Tree
Given a binary tree and a node, we need to write a program to find inorder successor of this node. Inorder Successor of a node in binary tree is the next node in Inorder traversal of the Binary Tree. Inorder Successor is NULL for the last node in Inorder traversal. In the below diagram, inorder successor of node 4 is 2, 1 is 3 and 5 is 1. Table of
12 min read
Inorder Traversal of Binary Tree
Inorder traversal is defined as a type of tree traversal technique which follows the Left-Root-Right pattern, such that: The left subtree is traversed firstThen the root node for that subtree is traversedFinally, the right subtree is traversed Examples of Inorder TraversalInput : .......A ............../ .......\ ...........B ...........COutput : B
7 min read
Convert Binary Tree to Doubly Linked List using inorder traversal
Given a Binary Tree (BT), the task is to convert it to a Doubly Linked List (DLL) in place. The left and right pointers in nodes will be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as the order of the given Binary Tree. The first node of Inorder traversal (leftmost node in BT) must be
15+ min read
Minimum swap required to convert binary tree to binary search tree
Given the array representation of Complete Binary Tree i.e, if index i is the parent, index 2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum number of swap required to convert it into Binary Search Tree. Examples: Input : arr[] = { 5, 6, 7, 8, 9, 10, 11 } Output : 3 Binary tree of the given array: Swap
8 min read
Difference between Binary Tree and Binary Search Tree
Binary Tree Data Structure:A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right children. Binary Search Tree Data Structure (BST):A binary search tree is a hierarchical data structure where each node has at most two children, wi
2 min read