二叉树篇
首先创建一个映射来存储中序遍历中值与索引的关系,然后通过递归调用函数dfs
来构建二叉树。函数dfs
接受前序遍历和中序遍历的左右边界索引以及前序遍历和中序遍历的列表和映射作为参数,在每次递归中,先判断边界条件,如果左边界等于右边界,则返回null
。然后计算左子树的大小,分别递归构建左子树和右子树,最后返回当前节点。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
Map<Integer, Integer> dict = new HashMap<>();
// 遍历 inorder 数组填充字典
for (int i = 0; i < inorder.length; i++) {
dict.put(inorder[i], i);
}
return dfs(0, preorder.length, 0, inorder.length, preorder, inorder, dict);
}
private TreeNode dfs(int preL, int preR, int inL, int inR, int[] preorder, int[] inorder, Map<Integer, Integer> dict) {
if (preL == preR) {
return null;
}
int rootVal = preorder[preL];
int rootIndexInorder = dict.get(rootVal);
int leftSize = rootIndexInorder - inL;
TreeNode left = dfs(preL + 1, preL + 1 + leftSize, inL, inL + leftSize, preorder, inorder, dict);
TreeNode right = dfs(preL + 1 + leftSize, preR, inL + 1 + leftSize, inR, preorder, inorder, dict);
return new TreeNode(rootVal, left, right);
}
}