题目
根据后序数组重建搜素二叉树
java代码
package com.lizhouwei.chapter3;
/**
* @Description:根据后序数组重建搜素二叉树
* @Author: lizhouwei
* @CreateDate: 2018/4/14 23:44
* @Modify by:
* @ModifyDate:
*/
public class Chapter3_14 {
public boolean isPostArray(int[] arr) {
return isPost(arr, 0, arr.length - 1);
}
public boolean isPost(int[] arr, int start, int end) {
if (start >= end) {
return true;
}
int value = arr[end];
int left = -1;
int right = end;
for (int i = 0; i < end; i++) {
if (value > arr[i]) {
left = i;//最后一个小于value的位置,一直在变化
} else {
//第一次出现大于value的位置,后面保持不动
right = right == end ? i : right;
}
}
//此时,说明在大于value的区间内有小于value的值,不是搜索二叉树树
if (left != right - 1) {
return false;
}
return isPost(arr, start, left) && isPost(arr, right, end - 1);
}
public Node rebuildBST(int[] arr) {
return buildBST(arr, 0, arr.length - 1);
}
public Node buildBST(int[] arr, int start, int end) {
if (start > end) {
return null;
}
int value = arr[end];
int left = -1;
int right = end;
for (int i = 0; i < end; i++) {
if (value > arr[i]) {
left = i;//最后一个小于value的位置
} else {
//第一次出现大于value的位置,后面保持不动
right = right == end ? i : right;
}
}
Node head = new Node(value);
head.left = buildBST(arr, start, left);
head.right = buildBST(arr, right, end - 1);
return head;
}
//测试
public static void main(String[] args) {
Chapter3_14 chapter = new Chapter3_14();
int[] arr1 = {1, 2, 3, 4, 6, 7, 0, 9, 5};
boolean res1 = chapter.isPostArray(arr1);
System.out.println("arr1{1, 2, 3, 4, 6, 7, 0, 9, 5}是否为后序遍历的数组:" + res1);
int[] arr2 = {1, 2, 3, 4, 6, 7, 8, 9, 5};
boolean res2 = chapter.isPostArray(arr2);
System.out.println("arr2{1, 2, 3, 4, 6, 7, 8, 9, 5}是否为后序遍历的数组:" + res2);
Node head = chapter.rebuildBST(arr2);
System.out.print("arr2{1, 2, 3, 4, 6, 7, 8, 9, 5}重构搜索二叉树后序打印");
NodeUtil.postOrder(head);
}
}
结果
![](https://images2018.cnblogs.com/blog/1369004/201804/1369004-20180415093011212-1866890182.png)