Topic 1367: Two fork search tree post-order traversal sequence time limit: 1 seconds memory limit: 32 trillion special sentence: No: 1359 resolution: 684 Title Description: Enter an array of integers to determine if the array is the result of a sequential traversal of a binary search tree. If yes, output yes, otherwise output No. Assume that any two digits of the input array are different. Input: Each test case consists of 2 rows: The first behavior is 1 integers n (1<=n<=10000), which represents the length of the array. The second line contains n integers, representing the array, and the range of the number in the array is [0,100000000]. Output: corresponding to each test case, if the input array is the result of a binary search tree after the sequential traversal output yes, otherwise output No. Sample input: 75 7 6 9 11 10 847 4 6 5 sample output: YesNo
#include <iostream> #include <stdio.h>using namespace std;//The last node is the root node, smaller than the root node in the left subtree, large in the right subtree bool VERIFYSQUENCEOFBST (int sequence[],int length) {if (sequence==null| | Length<=0) {return false; } int root = Sequence[length-1]; int i=0; for (; i<length-1;i++) {if (sequence[i]>root) {break; }} int j=i; for (; j<length-1;j++) {if (Sequence[j]<root) {return false; }}//Left dial hand tree is empty, is the search tree bool left = true; if (i>0) {left = Verifysquenceofbst (sequence,i); } bool right = TRUE; if (i<length-1) {right = Verifysquenceofbst (sequence+i,length-i-1); } return left&&right;} int main () {int n; while (scanf ("%d", &n)!=eof) {int* sequence = new Int[n]; for (int i=0;i<n;i++) {scanf ("%d", &sequence[i]); } if (Verifysquenceofbst (sequence,n)) {printf ("yes\n"); }else{printf ("no\n"); } } return 0;}
OJ Address
The sword refers to the offer series source code-two forks search tree sequential traversal sequence