剑指offer 二叉搜索树的后序遍历序列
问题描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
C++代码实现
思路:假设是二叉搜索树,二叉搜索树性质:右子树的值 > 根节点 > 左子树的值,所以找到左右子树的序列,满足条件则一直遍历下去,直到只有一个子节点为根节点。
class Solution {
public:
bool SquenceHelper(vector<int> squence, int left, int right)
{
if (left >= right)
return true;
int i;
for (i = left; i < right; i++)
if (squence[i] > squence[right])
break;
for (int j = i; j < right; j++)
if (squence[j] < squence[right])
return false;
return SquenceHelper(squence, left, i-1) && SquenceHelper(squence, i, right-1);
}
bool VerifySquenceOfBST(vector<int> sequence) {
if (sequence.size() == 0)
return false;
return SquenceHelper(sequence, 0, sequence.size() - 1);
}
};
python2代码实现
# -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
if sequence == []:
return False
#找到跟节点
i = 0
#找到左子树和右子树的分界点
while i < len(sequence) - 1:
if sequence[i] > sequence[-1]:
break
i += 1
for j in range(i,len(sequence)-1):
if sequence[j] < sequence[-1]:
return False
left = True
right = True
if i > 0:
left = self.VerifySquenceOfBST(sequence[:i])
if i < len(sequence) - 1:
right = self.VerifySquenceOfBST(sequence[i:len(sequence) - 1])
return left and right
java代码实现
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
if (sequence.length == 0)
return false;
return SquenceHelper(sequence, 0, sequence.length - 1);
}
public boolean SquenceHelper(int [] sequence, int left, int right) {
if (left >= right)
return true;
int i;
for (i = left; i < right; i++)
if (sequence[i] > sequence[right])
break;
for (int j = i; j < right; j++)
if (sequence[j] < sequence[right])
return false;
return SquenceHelper(sequence, left, i-1) && SquenceHelper(sequence, i, right - 1);
}
}