Skip to content

Commit ab5d6c4

Browse files
authored
Update bruteforce.cpp
外层while循环中需要判断(left == right),确定根节点左侧的序列是后序遍历序列。然后将left置为0,right--,重复循环,判断左移后的根节点左侧的序列仍是后序遍历序列。
1 parent 83ca915 commit ab5d6c4

File tree

1 file changed

+22
-32
lines changed

1 file changed

+22
-32
lines changed

024-二叉搜索树的后序遍历序列/bruteforce.cpp

Lines changed: 22 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -19,38 +19,28 @@ using namespace std;
1919
class Solution
2020
{
2121
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+
}
5444
};
5545

5646

0 commit comments

Comments
 (0)