Title: 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.
Idea: Need to traverse tree, binary sort tree is characterized by Lchild.key < Root.key < Rchild.key
Then we use the division of thought, first use the above characteristics to separate the left and right sub-tree, encountered the first greater than Root.key (right) is the rights subtree, then when we are traversing the right sub-tree when the situation is less than root.key, then it is the wrong sequence.
1#include"stdafx.h"2#include <stdio.h>3 4 5 //Bst:binary search tree, two forks6 BOOLVerifysquenceofbst (intSequence[],intlength)7 {8 if(sequence = = NULL | | length <=0)9 return false;Ten One introot = Sequence[length-1]; A - //The node of the left subtree in the binary search tree is smaller than the root node . - inti =0; the for(; i < length-1; ++i) - { - if(Sequence[i] >root) - Break; + } - + //The nodes of the right subtree in the binary search tree are larger than the root nodes . A intj =i; at for(; J < Length-1; ++j) - { - if(Sequence[j] <root) - return false; - } - in //determine if the left subtree is a binary search tree - BOOLleft =true; to if(I >0) +left =Verifysquenceofbst (sequence, i); - the //Judging right subtree is not binary search tree * BOOLright =true; $ if(I < length-1)Panax Notoginsengright = VERIFYSQUENCEOFBST (sequence + i, length-i-1) ; - the return(Left &&Right ); + } A the + intMain () - { $ $ //test1 - //Ten - // / the //6 - // /\ /Wuyi //4 8 the intData1[] = {4,8,6, A, -, -,Ten}; - intLength1 =sizeof(DATA1)/sizeof(int); Wuprintf"test1:"); - if(Verifysquenceofbst (data1, length1)) Aboutprintf"yes\n"); $ Else -printf"no\n"); - - //test2 A //5 + // / the //4 - // / $ //3 the // / the //2 the // / the //1 - in intData2[] = {5,4,3,2,1}; the intLength2 =sizeof(DATA2)/sizeof(int); theprintf"test2:"); About if(Verifysquenceofbst (data2, length2)) theprintf"yes\n"); the Else theprintf"no\n"); + - //test3 the //5Bayi // / the //4 7 the // / - //6 - the intData3[] = {4,6,7,5}; the intLength3 =sizeof(DATA3)/sizeof(int); theprintf"test3:"); the if(Verifysquenceofbst (data3, length3)) -printf"yes\n"); the Else theprintf"no\n"); the 94 //test4 the //NULL the theprintf"test4:");98 if(Verifysquenceofbst (NULL,0)) Aboutprintf"yes\n"); - Else101printf"no\n");102 103 return 0;104}
Sequential traversal sequence of binary search tree