Determination of binary search tree (C language version)

Without further ado, let’s get to the topic:

Given the inorder traversal sequence of a binary tree, ask whether this binary tree is a binary search tree.

Definition of binary search tree: Based on the definition of binary tree, the data domain of the left child node is less than or equal to the data domain of the root node, and the data domain of the right child node is greater than the data domain of the root node.

Input requirements:

The first line contains an integer n (1≤n≤50), indicating the number of nodes in the binary search tree;

The second line contains n integers ai (1≤ai≤100), representing the in-order traversal sequence. The data guarantees that sequence elements are distinct from each other.

Result is similar to this

  1. Sample 1

The corresponding binary tree is shown below, which is a binary search tree.

  1. Sample 2

The corresponding binary tree is as shown below, not a binary search tree.                                        

 code show as below:

#include <stdio.h>
#define MAXN 50
int n, a[MAXN], cnt = 0;
int isBST() {
    for (int i = 1; i < n; i++) {
        if (a[i] < a[i - 1])
            return 0;
    }
    return 1;}int isBSTree(int L, int R) {
    if (L > R)
        return 1;
    int i = L, j = R;
    while (i <= R && a[i] <= a[L])
        i++;
    while (j > L && a[j] >= a[L])
        j--;
    if (i - j != 1)
        return 0;
    return isBSTree(L + 1, j) && isBSTree(i, R);}
int main() {
    scanf("%d", &n);
    for (int i = 0; i < n; i++)
        scanf("%d", &a[i]);
    if (!isBST()) {
        printf("No\n");
        return 0;
    }
    printf(isBSTree(0, n - 1) ? "Yes\n" : "No\n");
    return 0;}

Guess you like

Origin blog.csdn.net/endofdestruction/article/details/132070510
Recommended