从前序与中序遍历序列构造二叉树1
给定一棵树的前序遍历 preorder 与中序遍历 inorder。请构造二叉树并返回其根节点。
package tree;
import java.util.HashMap;
import java.util.Map;
public class BuildTree {
/**
* 从前序与中序遍历序列构造二叉树
*
* @param preorder 前序遍历
* @param inorder 中序遍历
* @return 二叉树根结点
*/
public TreeNode buildTree(int[] preorder, int[] inorder) {
int preLen = preorder.length;
int inLen = inorder.length;
if (preLen != inLen) {
throw new RuntimeException("Incorrect input data.");
}
// 构造哈希映射,快速定位根节点
Map<Integer, Integer> rootIndexMap = new HashMap<>(preLen);
for (int i = 0; i < inLen; i++) {
rootIndexMap.put(inorder[i], i);
}
return buildTree(preorder, 0, preLen - 1, rootIndexMap, 0, inLen - 1);
}
/**
* 前序遍历: 根 左 (左子树结束位置) 右
* preLeft preLeft+1 pIndex - inLeft + preLeft preRight
* 中序遍历: 左 根 右
* inLeft pIndex inRight
* 左子树个数 = pIndex - inLeft =(左子树结束位置)- preLeft
*/
public TreeNode buildTree(int[] preorder, int preLeft, int preRight,
Map<Integer, Integer> rootIndexMap, int inLeft, int inRight) {
if (preLeft > preRight || inLeft > inRight) {
return null;
}
int rootVal = preorder[preLeft];
// 先把根节点建立出来
TreeNode root = new TreeNode(rootVal);
int pIndex = rootIndexMap.get(rootVal);
root.left = buildTree(preorder, preLeft + 1, pIndex - inLeft + preLeft,
rootIndexMap, inLeft, pIndex - 1);
root.right = buildTree(preorder, pIndex - inLeft + preLeft + 1, preRight,
rootIndexMap, pIndex + 1, inRight);
return root;
}
}
根据前序中序遍历序列中子树节点数量相等计算各个序列中左右子树的边界。