File tree Expand file tree Collapse file tree 1 file changed +22
-32
lines changed Expand file tree Collapse file tree 1 file changed +22
-32
lines changed Original file line number Diff line number Diff line change @@ -19,38 +19,28 @@ using namespace std;
19
19
class Solution
20
20
{
21
21
public:
22
- bool VerifySquenceOfBST (vector<int > sequence)
23
- {
24
- int left = 0 , right = sequence.size ( ) - 1 ;
25
- while (left < right && right != 0 )
26
- {
27
- // 前一半的元素都小于size
28
- while (sequence[left] < sequence[right])
29
- {
30
- left++;
31
- }
32
- // 循环结束时, left是第一个大于根的元素的位置
33
- //
34
- while (sequence[left] > sequence[right])
35
- {
36
- left++;
37
- }
38
-
39
- right--;
40
- }
41
-
42
- // 如果循环一直走到right == 0才终止, 说明满足后序遍历的定义
43
- if (right == 0 )
44
- {
45
- return true ;
46
- }
47
- else // 否则说明不满足递归的定义
48
- {
49
- return false ;
50
- }
51
-
52
-
53
- }
22
+ // 下面这种迭代的方法时间复杂度为O(n^2)
23
+ bool VerifySquenceOfBST_Iteratively (const vector<int >& sequence) {
24
+ int left = 0 , right = sequence.size () - 1 ;
25
+ while (left < right && right != 0 ) {
26
+ // 循环结束时,left是第一个大于根的元素的位置,即右子树首元素下标
27
+ while (sequence[left] < sequence[right])
28
+ left++;
29
+ // 循环结束时,left越过右子树末节点,到达根节点
30
+ while (sequence[left] > sequence[right])
31
+ left++;
32
+
33
+ // 如果没有到达根节点,说明不满足左子树所有节点小于根节点,右子树所有节点大于根节点的条件
34
+ if (left < right)
35
+ return false ;
36
+ left = 0 ;
37
+
38
+ right--;
39
+ }
40
+
41
+ // 如果循环一直到right == 0才终止, 说明以所有节点为根节点,左侧序列均满足后序遍历序列的条件
42
+ return (right == 0 ) ? true : false ;
43
+ }
54
44
};
55
45
56
46
You can’t perform that action at this time.
0 commit comments