剑指Offer算法实现之二十四:二叉搜索树的后续遍历序列
来源:互联网 发布:python均线策略结果 编辑:程序博客网 时间:2024/06/05 02:57
题目:输入一个整数数组,判断该数组是不是某个二叉搜索数的后续遍历的结果。如果是则返回true,否则返回false。假如输入的数组的任意两个数组都互不相同
思路:
后续遍历,最后一个元素为root。BST的特点是左子树所有节点小于等于root,右子树所有子节点均大于等于root。
递归,找到可能是左子树的序列,余下的为右子树的序列。判定候选的右子树序列是否满足大于等于root的条件。若满足,递归左右子树判断
编译环境:ArchLinux+Clang3.3,C++11
实现一:
#include <iostream>#include <cassert>using namespace std;bool checkSeqOfBST(int *seq, int len){ if (!seq || len < 1) return false; int root = seq[len - 1]; int *ptr = seq; int *end = seq + len - 1; // excluding while (ptr < end && *ptr <= root) ptr++; // 搜索[seq, end), 循环结束后,ptr左边为左子树(若有) int leftLen = ptr - seq; while (ptr < end) { // 遍历[ptr, end),初步验证是否为右子树 if (*ptr < root) return false; ptr++; } bool left = leftLen > 0 ? true : checkSeqOfBST(seq, leftLen); // 验证左子树 bool right = len - leftLen - 1 > 0 ? true : checkSeqOfBST(seq+leftLen, len - 1 - leftLen); // 验证右子树 return left && right;}int main(){ int a[] {5,7,6,9,11,10,8}; int b[] {7,4,6,5}; assert(checkSeqOfBST(a, sizeof(a)/sizeof(int))); assert(!checkSeqOfBST(b, sizeof(b)/sizeof(int)));}
- 剑指Offer算法实现之二十四:二叉搜索树的后续遍历序列
- 剑指Offer之 - 二叉搜索树的后续遍历序列
- 剑指offer系列之二十二:二叉搜索树的后续遍历序列
- [剑指Offer]二叉搜索树的后续遍历序列
- 剑指Offer--二叉搜索树的后续遍历序列
- 剑指offer-二叉搜索树的后续遍历序列
- 剑指offer面试题24:二叉搜索树的后续遍历序列 Java实现
- 【剑指 offer】(二十四)—— 二叉搜索树的后序遍历序列
- 【剑指offer】面试题24:二叉搜索树的后续前序遍历序列
- 剑指offer 4.3 举例形象化问题4-二叉搜索树的后续遍历序列
- 剑指offer面试题 二叉搜索树的后续遍历序列
- 剑指offer——二叉搜索树的后续遍历序列
- 【剑指Offer】面试题24:二叉搜索树的后续遍历序列
- 剑指offer——二叉搜索树的后续遍历序列
- 剑指offer 二叉树的后续遍历序列
- 剑指offer-二叉搜索树的后续遍历
- 【剑指offer】二叉搜索树的后续遍历
- 二叉搜索树的后续遍历序列
- char能表示(-128~127)
- Mplayer的移植
- 【回溯法】
- 15 steps to launch your own startup in Europe - Part 1
- matlab中冒号的用发
- 剑指Offer算法实现之二十四:二叉搜索树的后续遍历序列
- CEdit消除边框的创建
- Cocoa 关闭显示屏 (dim the display)
- 2440/6410+minitools+superboot烧写裸机新方法!
- 15 steps to launch your own startup in Europe - Part 2
- 战国七雄形势图
- Hi-Fi小经验(转)
- 分支限界法
- BS系统经验总结