forked from gatieme/CodingInterviews
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathispost_re.cpp
91 lines (74 loc) · 1.81 KB
/
ispost_re.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <iostream>
#include <vector>
using namespace std;
// 调试开关
#define __tmain main
#ifdef __tmain
#define debug cout
#else
#define debug 0 && cout
#endif // __tmain
class Solution
{
public:
bool VerifySquenceOfBST(vector<int> sequence)
{
if(sequence.size( ) == 0)
{
return false;
}
return judge(sequence, 0, sequence.size( ) - 1);
}
/// 2, 9, 5, 16, 17, 15, 19, 18, 12
bool judge(vector<int> &sequence, int left, int right)
{
if(left >= right)
{
return true;
}
/// 后一半的元素都比根元素大
int mid = right - 1;
while (sequence[mid] > sequence[right])
{
mid--;
}
/// 那么前面的元素都应该比根小
int i = left;
while (i < mid && sequence[i] < sequence[right])
{
i++;
}
if (i < mid)
{
return false;
}
#ifdef __tmain
printf("left : ");
for(int i = left; i <= mid; i++)
{
cout <<sequence[i] <<" ";
}
cout <<endl;
printf("right : ");
for(int i = mid + 1; i < right; i++)
{
cout <<sequence[i] <<" ";
}
cout <<endl;
cout <<"root : " <<sequence[right] <<endl;
#endif // __tmain
/// 这样我们就划分出区间
/// [left, mid] 是左子树
/// [mid + 1, right - 1] 是右子树
/// right 是根节点
return judge(sequence, left, mid) && judge(sequence, mid + 1, right - 1);
}
};
int __tmain( )
{
int a[] = { 2, 9, 5, 16, 17, 15, 19, 18, 12, };
vector<int> vec(a, a + 9);
Solution solu;
cout <<solu.VerifySquenceOfBST(vec) <<endl;
return 0;
}