剑指offer:二叉搜索树的后序遍历序列
补充知识:二叉搜索树是指父亲节点大于左子树中的全部节点,但是小于右子树中的全部节点的树;后序遍历是指按照 “左子树-右子树-根节点” 的顺序遍历
low和high分别对应数组得第一个元素和最后一个元素,同样也定义个start=low,因为start要往前遍历整个数组,if (sequence[i] <= sequence[high] )返回false,因为右子树是大于根结点的,然后把数组分成左子树、右子树、根三部分,最后 return VerifySquenceOfBSTCore(sequence, 0, sequence.size() - 1),判断满不满足!!!
class Solution { public: bool VerifySquenceOfBSTCore(vector<int>& sequence, int low, int high) { if (low >= high) return true;//左子树大于根节点,真 int start = low; while (start < high && sequence[start] < sequence[high]) ++start; for (int i = start; i < high; ++i) if (sequence[i] <= sequence[high] ) return false; return VerifySquenceOfBSTCore(sequence, low, start - 1) && VerifySquenceOfBSTCore(sequence, start, high-1); } bool VerifySquenceOfBST(vector<int> sequence) { if (sequence.empty()) return false; if (sequence.size() == 1) return true; return VerifySquenceOfBSTCore(sequence, 0, sequence.size() - 1); } };#剑指offr##23届找工作求助阵地#