当前位置:网站首页>【剑指offer33】二叉搜索树的后序遍历序列
【剑指offer33】二叉搜索树的后序遍历序列
2022-08-04 14:15:00 【星光技术人】
题目
解题思路
根据后续遍历数组的特性,最后一个元素为根节点,前边分为左右子树两部分,且左子树部分数组元素值小于根节点值,右子树部分数组元素大于根节点值
- code【自解】
class Solution {
public:
bool verifyPostorder(vector<int>& postorder) {
if(postorder.size()==0)
return true;
return process(postorder,0,postorder.size()-1);
}
bool process(vector<int>& postorder,int start,int end)
{
bool flag = true; //标记以postorder[end]为根节点的树有没有右子树
int temp = start-1; //左子树数组最后一个元素索引
//basecase
//当子树只包含一个元素时,一定true
if(start == end)
return true;
//判断是否有右子树
//根据后序遍历的数组特性,根节点postorder[end-1]的前驱节点为postorder[end-1]
//如果 postorder[end-1] > postorder[end]说明右子树存在
if(postorder[end-1] > postorder[end])
flag = false;
//无右子树,那么根节点postorder[end]前边的所有元素不能大于postorder[end]
if(flag)
{
for(int i=end-1;i>=start;i--)
{
if(postorder[i] > postorder[end])
return false;
}
}
//有右子树,那么就需要寻找左右子树的分界值
for(int i=end-1;i>=start;i--)
{
if(postorder[i]<postorder[end])
{
//temp为最后一个左子树元素值
temp = i;
break;
}
}
//分界索引temp前边的所用元素都属于postorder[end]的左子树,所以值不能大于根节点值
for(int i=temp;i>=start;i--)
{
if(postorder[i] > postorder[end])
return false;
}
bool res = true;
if(start <= temp)
res = res && process(postorder,start,temp);
if(temp+1 <= end-1)
res = res && process(postorder,temp+1,end-1);
return res;
}
};
- code 【官方】
class Solution {
public:
bool verifyPostorder(vector<int>& postorder) {
return process(postorder,0,postorder.size()-1);
}
bool process(vector<int>& postorder,int start,int end)
{
if(start>=end)
return true;
int cur = postorder[end];
int p = start;
while(postorder[p] < cur) p++;
int m = p;
while(postorder[m] > cur) m++;
return m==end && process(postorder,start,p-1) && process(postorder,p,end-1);
}
};
边栏推荐
猜你喜欢
随机推荐
odoo15 大部分模块都用的附件整理成一独立模块
理论篇1:深度学习之----LetNet模型详解
【 HMS core 】 【 Media 】 online video editing service 】 【 material can't show, or network anomalies have been Loading state
Qt的QItemDelegate使用
ssm learning experience (final chapter)
Chinese valentine's day, of course, to learn SQL optimization better leave work early to find objects
浙江大学团队使用基于知识图谱的新方法,从空间分辨转录组数据中推断细胞间通信状况
如何在ubuntu环境下安装postgresql并配置远程访问
国家安全机关对涉嫌危害国家安全犯罪嫌疑人杨智渊实施刑事拘传审查
leetcode 48. Rotate Image 旋转图像(Medium)
快解析结合千方百剂
SQL语句的写法:Update、Case、 Select 一起的用法
AVR学习笔记之熔丝位
《社会企业开展应聘文职人员培训规范》团体标准在新华书店上架
SLAM 05.视觉里程计-2-特征法
集合划分差最小问题(01背包)
九州云出席领航者线上论坛,共话5G MEC边缘计算现状、挑战和未来
从理论到实践:MySQL性能优化和高可用架构,一次讲清
字符串类的设计与实现_C语言字符串编程题
基于 Next.js实现在线Excel