二叉搜索树的后序遍历序列

题目:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则返回true,否则返回false。假设输入的数组的任意两个数字都互不相同。

 1 // Type your C++ code and click the "Run Code" button!
 2 // Your code output will be shown on the left.
 3 // Click on the "Show input" button to enter input data to be read (from stdin).
 4 
 5 #include <iostream>
 6 using namespace std;
 7 bool VerifySquenceOfBST( int data[], int len )
 8 {
 9     if( data == NULL || len <= 0 )
10     {
11         return false;
12     }
13     
14     int root = data[ len - 1 ];
15     int i=0;
16     int j;
17     
18     for( ; i < len - 1; i++ )
19     {
20         if( data[i] > root )
21         {
22             break;
23         }
24     }
25     
26     j = i;
27     
28     for( ; j < len - 1; j++ )
29     {
30         if( data[j] < root )
31         {
32             return false;
33         }
34     }
35     
36     bool left = true;
37     bool right = true;
38     
39     if( i > 0 )
40     {
41         left =VerifySquenceOfBST( data, i ); 
42     }
43     
44     if( i < len - 1 )
45     {
46         right=VerifySquenceOfBST( data+i, len - i - 1 );
47     }
48     
49     return ( left && right );
50 }
51 int main() {
52     // Start typing your code here...
53     cout << "Hello world!" << endl;
54     
55     
56     return 0;
57 }

 

posted @ 2013-07-23 09:49  NinaGood  阅读(121)  评论(0编辑  收藏  举报