Data structure exercises: Determine whether it is the suffix of a binary search tree

topic:

【问题描述】输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。如果是返回true,否则返回false。
【输入形式】输入任意长度的数组,数字之间空格分开
【输出形式】true 或者 false
【样例输入】输入  5 7 6 9 11 10 8
【样例输出】true
【样例说明】由于这一整数序列是如下树的后序遍历结果:

         8
       /  \
      6    10
    / \    / \
   5   7   9  11

因此返回true。

【评分标准】暴力求解法不得分。

Ideas:

  1. When I did this question, I didn’t turn around. I thought that the in-order structure can be obtained according to the sorting. With the follow-up and in-order, a tree can be built, and then I can judge whether the tree is a binary sort tree. But this idea is wrong
  2. The correct idea is actually very simple:
    check the suffix expression, the last one is the root, search the tree and traverse the array in order, from the head of the array to the first node larger than the root is the left child, and the right child must all be greater than the root, recursive , If the right child is not greater than the root, the suffix traversal is wrong
  3. pre(int las[], int start, int index)This function is a recursive function, start-index is the suffix range to be traversed at this time, index is the root of this range, for example, at 5 7 6 9 11 10 8the beginning start = 0, index = 6, where las[index] is the root of this range
  4. find_min(int las[], int start, int index)This function is to find the first node that is greater than or equal to the root, and then use this point to divide the scope — essentially splitting the left and right child nodes of the root
  5. Recursion to the left and right sub-ranges at the end

Code:

#include <stdio.h>
#include <stdlib.h>

int find_min(int las[], int start, int index) {
    
    
    for (int i = start; i < index; i++) {
    
    
        if (las[i] >= las[index]) {
    
    
            return i;
        }
    }
}

int pre(int las[], int start, int index) {
    
      // index为后缀遍历时对应的根的
    // printf("start = %d   index = %d\n", start, index);
    if (start < index) {
    
    
        // printf("index = %d\n", index);
        int end = find_min(las, start, index);  // 刚比las[index]大或者等的下标
        // printf("end = %d\n", end);
        for (int i = end; i < index; i++) {
    
    
            if (las[i] < las[index]) {
    
    
                return 0;
            }
        }
        pre(las, start, end - 1);
        // printf("sss end = %d\n", end);
        pre(las, end, index - 1);
    }
    return 1;
}


int main() {
    
    
    int las[40];
    int l_num = 0;  // 字符的个数
    do {
    
    
        scanf("%d", &las[l_num++]);
    } while (getchar() != '\n');
    // printf("%d\n", l_num);
    if (pre(las, 0, l_num - 1)) {
    
    
        printf("true");
    }
    else
        printf("false");
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_43779658/article/details/106604339