Check if an array represents Inorder of Binary Search tree or not

1.7

Given an array of N element. The task is to check if it is Inorder traversal of any Binary Search Tree or not. Print “Yes” if it is Inorder traversal of any Binary Search Tree else print “No”.

Examples:

Input : arr[] = { 19, 23, 25, 30, 45 }
Output : Yes

Input : arr[] = { 19, 23, 30, 25, 45 }
Output : No

The idea is to use the fact that the inorder traversal of Binary Search Tree is sorted. So, just check if given array is sorted or not.

// C++ program to check if a given array is sorted
// or not.
#include<bits/stdc++.h>
using namespace std;

// Function that returns true if array is Inorder
// traversal of any Binary Search Tree or not.
bool isInorder(int arr[], int n)
{
    // Array has one or no element
    if (n == 0 || n == 1)
        return true;

    for (int i = 1; i < n; i++)

        // Unsorted pair found
        if (arr[i-1] > arr[i])
            return false;

    // No unsorted pair found
    return true;
}

// Driver code
int main()
{
    int arr[] = { 19, 23, 25, 30, 45 };
    int n = sizeof(arr)/sizeof(arr[0]);
    
    if (isInorder(arr, n))
        cout << "Yesn";
    else
        cout << "Non";
        
  return 0;
}

Output:

Yes

This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



1.7 Average Difficulty : 1.7/5.0
Based on 13 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.