/*
第 9 题
判断整数序列是不是二元查找树的后序遍历结果
题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。
如果是返回 true,否则返回 false。
例如输入 5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
8
/ \
6 10
/ \ / \
5 7 9 11
因此返回 true。
如果输入 7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回 false。
记住是二元查找树 根大于左边 小于右边而且是后序,
所以思序列最后一个必是根节点,从前往后遍历,比根节点小的都是其左子树,
并且位于序列的左半部分,比其大的为其右子树,应该位于其右半部分。
递归左右子树按上述思路分别进行判断。
*/
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
void test(int data[],int st,int end,bool &flag)
{
if(flag&&st<end)
{
int left=st;
while(data[end]>data[left]) left++;//取左子树
for(int j=left;j<end;j++)// 判断右子树是否合格
{
if(data[j]<data[end])
{
flag=false;return;
}
}
test(data,0,left-1,flag);// 递归判断
test(data,left,end-1,flag);
}
}
int main(){
int a[]={5,7,6,9,11,10,8};
bool flag=true;
test(a,0,6,flag);
if(flag) cout<<"yes"<<endl;
else cout<<"no"<<endl;
int b[]={7,4,6,5};
test(b,0,3,flag);
if(flag) cout<<"yes"<<endl;
else cout<<"no"<<endl;
return 0;
}
9 判断整数序列是不是二元查找树的后序遍历结果
原创
©著作权归作者所有:来自51CTO博客作者我想有个名字的原创作品,请联系作者获取转载授权,否则将追究法律责任
上一篇:10 翻转句子中单词的顺序。
下一篇:线段相交 算法摘记
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
树(4)判断某个序列是否是二叉查找树的后序遍历结果
最后一个元素是根节点 然后根据搜索二叉树性质划分为: 根左子
二叉树 遍历 搜索 子树 结点 -
二元查找树
二元查找树是指一棵空树或者具
子树 结点 查找树 -
程序员面试50题(2)—二元查找树的后序遍历结果[数据结构]
题目:输入一个整数数组,判断该数组是不是
数据结构 算法 结点 后序遍历 查找树 -
二元查找树的后序遍历结果
题目:输入一个整数数组,判断该数组是不是某二元查找树的
后序遍历 查找树 #include 数组 插入节点