题目描述
输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
题目链接:https://leetcode.cn/problems/zhong-jian-er-cha-shu-lcof/description/
解答
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
// 定义类内公用集合
private HashMap<Integer, Integer> indexMap;
public TreeNode buildTree(int[] preorder, int[] inorder) {
// 数据准备
int len = preorder.length;
indexMap = new HashMap<Integer, Integer>();
for (int i = 0; i < len; i++) {
// key-value对应键为二叉树节点,值为中序遍历数组下标
indexMap.put(inorder[i], i);
}
// 最初的下标包括整个先序和中序数组
return recursionBuildTree(preorder, inorder, 0, len-1, 0, len-1);
}
// 递归创建树,参数为先序数组,中序数组,先序数组左右索引,中序数组左右索引
public TreeNode recursionBuildTree(int[] preorder, int[] inorder, int preorderLeftIndex, int preorderRightIndex, int inorderLeftIndex, int inorderRightIndex) {
if (preorderLeftIndex > preorderRightIndex) return null;
// 获取先序中根的索引
int preorderRootIndex = preorderLeftIndex;
// 获取中序中根的索引
int inorderRootIndex = indexMap.get(preorder[preorderRootIndex]);
// 创建根节点
TreeNode root = new TreeNode(preorder[preorderRootIndex]);
// 求左子树长度,即节点数
int leftSubtreeLength = inorderRootIndex - inorderLeftIndex;
// 调整左子树在先序和中序数组中的范围
root.left = recursionBuildTree(preorder, inorder, preorderLeftIndex+1, preorderLeftIndex+leftSubtreeLength, inorderLeftIndex, inorderRootIndex-1);
// 调整右子树在先序和中序数组中的范围
root.right = recursionBuildTree(preorder, inorder, preorderLeftIndex+leftSubtreeLength+1, preorderRightIndex, inorderRootIndex+1, inorderRightIndex);
return root;
}
}