二叉搜索树的后序遍历:给出一个序列,判断其是不是二叉搜索树的后序遍历。(先遍历左子节点,再遍历右子节点,最后遍历根节点)
python实现:
# -*- coding:utf-8 -*-
class Solution:
def VerifySquenceOfBST(self, sequence):
# write code here
length = len(sequence)
if sequence is None or length == 0:
return False
root = sequence[length-1]
i = 0
while i<length-1:
if sequence[i] > root:
break
i += 1
for j in range(i,length-1):
if sequence[j]<root:
return False
left = True
right = True
if i > 0:
left = self.VerifySquenceOfBST(sequence[:i])
if i < length-1:
right = self.VerifySquenceOfBST(sequence[i:length-1])
return left and right
C++实现:
class Solution {
public:
bool VerifySquenceOfBST(vector<int> sequence) {
int length = sequence.size();
if(length == 0){
return false;
}
return verify(sequence,length,0);
}
bool verify(vector<int> sequence,int length,int start){
int root = sequence[length-1];
int i = start;
for(;i<length-1;i++){
if(sequence[i]>root){
break;
}
}
int j = i;
for(;j<length-1;j++){
if(sequence[j]<root){
return false;
}
}
bool left = true;
bool right = true;
if(i>0){
left = verify(sequence,i,start);
}
if(i<length-1){
right = verify(sequence,length-i-1,i);
}
return (left && right);
}
};
序列的最后一个节点为树的根节点,从序列的头部开始依次将节点与根节点的值进行比较,如果大于根节点,则停止循环,得到右子树的首节点。从右子树的首节点开始与根节点的值进行比较,如果出现比根节点值小的节点,则返回false。最后用递归再判断左子序列和右子序列是否符合标准。
代码地址