# 剑指offer--二叉搜索树的后序遍历序列

511人阅读 评论(0)

AC代码：

import java.util.Arrays;

public class Solution {
public boolean VerifyLeftTree(int[] leftsequence , int root){
boolean flag = true;
for ( int i = 0 ; i < leftsequence.length ; i++){
if ( leftsequence[i] >= root){
flag = false;
break;
}
}
return flag;
}

public boolean VerifyRightTree(int[] rightsequence , int root){
boolean flag = true;
for ( int i = 0 ; i < rightsequence.length ; i++){
if ( rightsequence[i] <= root){
flag = false;
break;
}
}
return flag;
}

//判断sequence是否已经有序
public boolean IsOrder(int [] sequence){
//判断是否已经是升序
int[] tmp = Arrays.copyOfRange(sequence, 0, sequence.length);
Arrays.sort(tmp);
boolean flag1 = true;
for(int i = 0 ; i < sequence.length ; i++){
if ( sequence[i] != tmp[i]){
flag1 = false;
break;
}
}

//判断是否已经是降序
int cnt = 0;
boolean flag2 = true;
for ( int i = tmp.length-1 ; i >= 0 ; i--){
if ( sequence[cnt++] != tmp[i]){
flag2 = false;
break;
}
}

boolean flag = flag1 || flag2;
return flag;
}

public boolean VerifySquenceOfBST(int [] sequence) {
int partition = 0;
int len = sequence.length;
if ( sequence == null || len == 0){
return false;
}

int root = sequence[len-1];
if ( IsOrder(sequence)){
return true;
}

for ( int i = 0 ; i < len-1 ; i++){
if (sequence[i] < root && sequence[i+1] > root){
partition = i;
break;
}
}

int[] left = Arrays.copyOfRange(sequence, 0, partition+1);
int[] right = Arrays.copyOfRange(sequence, partition+1, len-1);

for ( int i = 0 ; i < left.length ; i++){
System.out.print(left[i]+" ");
}
System.out.println();
for ( int i = 0 ; i < right.length ; i++){
System.out.print(right[i]+" ");
}
boolean leftflag = VerifyLeftTree(left,root);
boolean rightflag = VerifyRightTree(right,root);
boolean flag = leftflag & rightflag;
return flag;
}
}
1
0

个人资料
• 访问：155743次
• 积分：4932
• 等级：
• 排名：第6843名
• 原创：329篇
• 转载：0篇
• 译文：0篇
• 评论：81条
博客专栏
 数据结构与算法 文章：71篇 阅读：32674
 面试在线编程专栏 文章：71篇 阅读：31096
 数学建模专栏 文章：11篇 阅读：32006
 机器学习数据挖掘笔记 文章：10篇 阅读：10084
最新评论