题目来源“数据结构与算法面试题80道”。在此给出我的解法,如你有更好的解法,欢迎留言。
根据二叉查找树的定义,二叉查找树或者是一棵空二叉树,或者是具有一下特性的二叉树:
结合二叉树的后序遍历,则初始序列的最后一位为树的根节点。
bool judge_is_search_tree(int *a, int start, int end) {
if (start == end) return true;
if (start > end) return false;
int root = a[end - 1];
int i = start;
while (i < end-1 && a[i] < root) i++;
int pos = i;
while (i < end-1) {
if (a[i] < root) return false;
i++;
}
bool left = judge_is_search_tree(a, 0, pos);
bool right = judge_is_search_tree(a, pos, end-1);
return left&&right;
}