剑指Offer-- 二叉搜索树的后序遍历序列判断
版本1:C++
class Solution { public: bool VerifySquenceOfBST(vector<int> sequence) { if (sequence.size() == 0) return false; int len = sequence.size(),i = 0,j; int root = sequence[len - 1]; // 根节点 vector<int> leftTree, rightTree; while (sequence[i] < root){ // 找出左子树的范围 0 ~ i-1 leftTree.push_back(sequence[i]); // 将左子树存入一个vector i++; } for (j = i; j < len - 1; j++){ // 在右子树的范围 j ~ len-1 内判断有没有不合理的数字 if (sequence[j] < root){ return false; } rightTree.push_back(sequence[j]); // 将右子树存入一个vector } bool resofleft = true, resofright = true; // 这里的初始化重要,是控制判断为真情况的 if (leftTree.size() > 0){ // 保证子树为空时能够跳过判断 resofleft = VerifySquenceOfBST(leftTree); // 递归判断左子树 } if (rightTree.size() > 0){ resofright = VerifySquenceOfBST(rightTree); // 递归判断右子树 } return (resofleft && resofright); // 左右子树都返回为真时,才为真 } };
版本2:python
# -*- coding:utf-8 -*- class Solution: def VerifySquenceOfBST(self, sequence): # write code here if not sequence: return False leng = len(sequence) root = sequence[leng - 1] i = 0 ltree = [] rtree = [] while sequence[i] < root: ltree.append(sequence[i]) i = i + 1 j = i for j in range(j, leng - 1): if sequence[j] < root: return False rtree.append(sequence[j]) leftTree = True rightTree = True if len(ltree) : leftTree = self.VerifySquenceOfBST( ltree) if len(rtree) : rightTree = self.VerifySquenceOfBST( rtree) return (leftTree and rightTree)