
剑指offer Leetcode 33. 二叉搜索树的后序遍历序列
发布日期:2021-05-06 23:39:31
浏览次数:27
分类:精选文章
本文共 1708 字,大约阅读时间需要 5 分钟。
前序遍历结果和此题很类似,不同点在于前序遍历得到的序列中,第一个数字是根节点的值
解法1:递归
递归思想:
●终止条件:
//left > right:当左子树为空时,mid = left,传入函数会出现left > right的情况,这种情况返回true //left = right与left = right - 1:任意一个或两个数可以构成二叉树的后序遍历,返回true if(left >= right - 1) return true;
●递推工作
序列的最后一个节点为根的值,从左开始遍历,连续的小于根值的序列就是左子树序列,连续的大于根值的序列就是右子树序列。如果index != right,说明不满足条件。

●返回值
一个序列是否合法,需要判断序列能否完整分成左子树、右子树和根(判断index == right),并且左子树合法,右子树合法。
复杂度:
●时间复杂度:O(N2),每次递归减去一个根节点,需要O(N)轮,最差情况下退化为链表,每轮需要遍历所有节点,需要O(N),所以最坏需要O(N2)
●空间复杂度:退化为链表时,需要N层递归,O(N)
代码:
class Solution { public: bool verifyPostorder(vector & postorder) { return verifyPostorder_boundary(postorder, 0, postorder.size() - 1); } bool verifyPostorder_boundary(vector & postorder, int left, int right){ //left > right:当左子树为空时,mid = left,传入函数会出现left > right的情况,这种情况返回true //left = right与left = right - 1:任意一个或两个数可以构成二叉树的后序遍历,返回true if(left >= right - 1) return true; int root_val = postorder[right]; int index = left; //此处获得左子树,遇到>=的就跳出 while(postorder[index] < root_val) index++; //mid将left和right隔为两个新的区间 int mid = index; while(postorder[index] > root_val) index++; //如果没出错,index应该在right跳出循环,所以判断index == right //新的左子树区间为[left, mid - 1],因为index++所以mid要减去1 //新的右子树区间为[mid, right - 1],因为right处为root,所以去掉 return index == right && verifyPostorder_boundary(postorder, left, mid - 1) && verifyPostorder_boundary(postorder, mid, right - 1); }};
解法2:单调栈
https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/solution/mian-shi-ti-33-er-cha-sou-suo-shu-de-hou-xu-bian-6/
发表评论
最新留言
很好
[***.229.124.182]2025年04月15日 05时40分24秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
《非暴力沟通》总结
2021-05-09
《你当像鸟飞往你的山》总结
2021-05-09
《我是猫》总结
2021-05-09
《抗糖化书》总结
2021-05-09
apache虚拟主机配置
2021-05-09
光盘作为yum源
2021-05-09
PHP 正则表达式资料
2021-05-09
PHP官方网站及PHP手册
2021-05-09
mcrypt加密以及解密过程
2021-05-09
mysql连续聚合
2021-05-09
go等待N个线程完成操作总结
2021-05-09
消息队列 RocketMQ 并发量十万级
2021-05-09
ReactJs入门教程-精华版
2021-05-09
乐观锁悲观锁应用
2021-05-09
.net Core 使用IHttpClientFactory请求
2021-05-09
多线程之旅(准备阶段)
2021-05-09
Python 之网络式编程
2021-05-09
MySql5.5安装步骤及MySql_Front视图配置
2021-05-09