【剑指OFFER】面试题33. 二叉搜索树的后序遍历序列
发布日期:2021-06-29 19:46:22 浏览次数:2 分类:技术文章

本文共 1030 字,大约阅读时间需要 3 分钟。

题目:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。

参考以下这颗二叉搜索树:

5    / \   2   6  / \ 1   3

示例 1:

输入: [1,6,3,2,5]

输出: false

示例 2:

输入: [1,3,2,6,5]

输出: true

提示:

数组长度 <= 1000

答案

class Solution {
public boolean verifyPostorder(int[] postorder) {
//递归判断左子树右子树是否满足条件 if(postorder.length == 0 || postorder.length == 1) return true; int index = postorder.length - 1; for(int i = 0; i < postorder.length; i++){
if(postorder[i] > postorder[postorder.length - 1] && index == postorder.length - 1){
index = i; } if(i > index){
if(postorder[i] < postorder[postorder.length - 1]) return false; } } int[] p1 = new int[index]; int[] p2 = new int[postorder.length - index - 1]; System.arraycopy(postorder, 0, p1, 0, index); System.arraycopy(postorder, index, p2, 0, postorder.length - index - 1); return verifyPostorder(p1) && verifyPostorder(p2); }}

转载地址:https://darkness.blog.csdn.net/article/details/105810901 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【剑指OFFER】面试题34. 二叉树中和为某一值的路径
下一篇:【力扣】200. 岛屿数量

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年05月02日 12时15分29秒