数据结构(七十五)
学习数据结构与算法过程中的心得体会以及知识点的整理,方便我自己查找,也希望可以和大家一起交流。
—— 二叉搜索树的后序遍历序列 ——
1.题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
参考以下这颗二叉搜索树:
5
/ \
2 6
/ \
1 3
示例
输入:
[1,6,3,2,5]
输出:
false
输入:
[1,3,2,6,5]
输出:
true
2.代码
c
bool verifyPostorder(int* postorder, int postorderSize){
int i, index = 0;
if (postorderSize <= 1)
return true;
for (i = 0; i < postorderSize; i++)
if (postorder[i] > postorder[postorderSize - 1]) {
index = i;
break;
}
for (; i < postorderSize - 1; i++)
if (postorder[i] <= postorder[postorderSize - 1])
return false;
return verifyPostorder(postorder, index) && verifyPostorder(postorder + index, postorderSize - index - 1);
}