package com.my.util;
/**
* 二叉树的节点
* */
public class TreeNode {
public int value;
public TreeNode left;
public TreeNode right;
public TreeNode(int data) {
this.value = data;
}
}
已知先序和中序序列,重建二叉树
package com.my.offer;
import com.my.util.TreeNode;
/**
* 重建二叉树:已知先序和中序序列
* @author asus
*
*/
public class Solution04 {
/**
* 已知先序和中序,重建二叉树
* @param pre
* @param in
* @return
*/
public TreeNode rebuildBinaryTree(int[] pre, int[] in) {
//边界条件判断
if(pre == null || in == null) {
return null;
}
//递归的找到二叉树的根节点,并将根节点返回
TreeNode root = rebuildBinaryTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
return root;
}
/**
* 根据先序和中序找到根节点和左右子树
* @param pre
* @param startP
* @param endP
* @param in
* @return
*/
private TreeNode rebuildBinaryTree(int[] pre, int startP, int endP, int[] in, int startI, int endI) {
//递归结束条件
if(startP > endP || startI > endI) {
return null;
}
//根据先序序列找到根节点
TreeNode root = new TreeNode(pre[startP]);
//遍历中序序列,找到该根节点的左子树和右子树
for(int i = startI; i <= endI; i++) {
if(in[i] == pre[startP]) {
//说明下标i对应的元素为根节点,i左边为左子树,i右边为右子树
root.left = rebuildBinaryTree(pre, startP + 1, startP + (i - startI), in, startI, i - 1);
root.right = rebuildBinaryTree(pre, startP + (i - startI) + 1, endP, in, i + 1, endI);
}
}
return root;
}
}
已知中序和后序序列,重建二叉树
package com.my.offer;
import com.my.util.TreeNode;
/**
* 重建二叉树:已知中序后后序序列
* @author asus
*
*/
public class Solution05 {
/**
* 已知先序和中序,重建二叉树
* @param in
* @param post
* @return
*/
public TreeNode rebuildBinaryTree(int[] in, int[] post) {
//边界条件判断
if(in == null || post == null) {
return null;
}
//递归的找到二叉树的根节点
TreeNode root = rebuildBinaryTree(in, 0, in.length - 1, post, 0, post.length - 1);
return root;
}
private TreeNode rebuildBinaryTree(int[] in, int startI, int endI, int[] post, int startP, int endP) {
//递归结束条件
if(startI > endI || startP > endP) {
return null;
}
//根据后序序列找到根节点
TreeNode root = new TreeNode(post[endP]);
//遍历中序序列,找到该根节点的左子树和右子树
for(int i = startI; i <= endI; i++) {
if(in[i] == post[endP]) {
//说明i下标对应的元素是根节点,该下标左边为左子树,该下标右边为右子树
root.left = rebuildBinaryTree(in,startI, i - 1, post, startP, startP + (i - startI) - 1);
root.right = rebuildBinaryTree(in,i + 1, endI , post, startP + (i - startI), endP - 1);
}
}
return root;
}
}