之前写过二叉树重构的C++实现,下面的是Java实现基本原理还是递归。
package com.mars.binaryree;
import java.util.Arrays;
/**
* 二叉树重构
* @author Mars
*
*/
public class Solution {
public static void main(String[] args) {
int[] pre = {1,2,4,7,3,5,6,8};
int[] in = {4,7,2,1,5,3,8,6};
int[] post = {7,4,2,5,8,6,3,1};
Solution solution = new Solution();
// TreeNode root = solution.reConstructBinaryTree(pre, in);
TreeNode root = solution.reConstructBinaryTreeByPostAndIn(post, in);
solution.PrintPreorder(root);
}
/**
* 先序遍历二叉树
* @param root
*/
private void PrintPreorder(TreeNode root) {
if(root == null)
return;
System.out.print(root.val+" ");
PrintPreorder(root.left);
PrintPreorder(root.right);
}
/**
* 根据先序遍历和中序遍历数组重构二叉树
* @param pre 先序遍历数组
* @param in 中序遍历数组
* @return 二叉树根节点
*/
public TreeNode reConstructBinaryTree(int [] pre, int [] in) {
//数组为空直接返回null
if(0 == pre.length || 0 == in.length)
return null;
//先序遍历数组的第一个元素作为根节点
TreeNode root = new TreeNode(pre[0]);
//在根节点在中序遍历数组中的位置,初始化为-1
int index = -1;
for(int i = 0; i < in.length; ++i){
if(root.val == in[i]){
index = i;
break;
}
}
/*
* pre[] 被分成左右两部分leftPre:[1...index], rightPre:[index+1...pre.length-1]
* in[] 被分成左右两部分leftIn:[0...index-1], rightIn:[index+1...in.lenght-1]
*/
int[] leftPre = Arrays.copyOfRange(pre, 1, index + 1);
int[] leftIn = Arrays.copyOfRange(in, 0, index);
int[] rightPre = Arrays.copyOfRange(pre, index+1, pre.length);
int[] rightIn = Arrays.copyOfRange(in, index+1, in.length);
//分别对左右子树进行递归
root.left = reConstructBinaryTree(leftPre, leftIn);
root.right = reConstructBinaryTree(rightPre, rightIn);
return root;
}
/**
* 根据后序遍历和中序遍历重构二叉树
* @param post 后序遍历数组
* @param in 中序遍历数组
* @return 重构的二叉树根节点
*/
public TreeNode reConstructBinaryTreeByPostAndIn(int[] post, int[] in){
if(0 == post.length || 0 == in.length)
return null;
TreeNode root = new TreeNode(post[post.length-1]);
int index = -1;
for(int i = 0; i < in.length; ++i){
if(root.val == in[i]){
index = i;
break;
}
}
/*
*post[]被分成左右两部分,leftPost:[0...index-1], rightPost:[index...post.lenght-2]
*in[]被分成左右两部分 leftIn:[0...index-1], rightIn:[index+1...in.lenght-1]
*/
int[] leftPost = Arrays.copyOfRange(post, 0, index);
int[] rightPost = Arrays.copyOfRange(post, index, post.length-1);
int[] leftIn = Arrays.copyOfRange(in, 0, index);
int[] rightIn = Arrays.copyOfRange(in, index+1, in.length);
root.left = reConstructBinaryTreeByPostAndIn(leftPost, leftIn);
root.right = reConstructBinaryTreeByPostAndIn(rightPost, rightIn);
return root;
}
}
TreeNode的定义如下:
package com.mars.binaryree;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}