Problem description:Enter an integer array to determine whether the array is the result of the sequential traversal of a binary search tree. If true is returned, otherwise false is returned. For example, input 4, 8, 6, 12, 16, 14, 10, because the integer sequence is the result of the post-order traversal of the following tree: 10
/\
6 14
/\/\
4 8 12 16 therefore, true is returned. If you enter 6, 5, 8, 5, 7, false is returned.
Analysis:
In the subsequent traversal sequence, the last element is the root node of the tree. The root node element divides the array into two parts. The left side is smaller than the root node, and the right side is greater than the root node. Recursively determine whether the left and right are binary search trees.
Code implementation:
1 // 9.cc 2 # include <iostream> 3 using namespace STD; 4 5 bool verify (int * a, int size) {6 if (null = A | size <= 0) 7 return false; 8 9 int root = A [size-1]; 10 11 // The left node is smaller than the root node 12 INT I = 0; 13 while (I <size-1 & A [I] <= root) 14 I ++; 15 16 // The right node is 17 for (Int J = I; j <size-1; j ++) {18 if (a [J] <root) 19 Return false; 20} 21 22 // verify left and right subtree 23 bool left = true; 24 if (I> 0) 25 left = verify (A, I ); 26 27 bool right = true; 28 if (I <size-1) 29 right = verify (a + I, size-I-1 ); 30 31 return (left & right); 32} 33 34 int main () {35 int A [] = {4, 8, 6, 12, 16, 14, 10}; 36 int size = sizeof (a)/sizeof (INT); 37 bool flag = verify (A, size); 38 cout <flag <Endl; 39 return 0; 40}