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
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
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
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
Recursion to the left and right sub-ranges at the end
Code:
#include<stdio.h>#include<stdlib.h>intfind_min(int las[],int start,int index){
for(int i = start; i < index; i++){
if(las[i]>= las[index]){
return i;}}}intpre(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]){
return0;}}pre(las, start, end -1);// printf("sss end = %d\n", end);pre(las, end, index -1);}return1;}intmain(){
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");}elseprintf("false");return0;}