1. 问题描述
给定两个整数数组 preorder
和 inorder
,其中 preorder
是二叉树的先序遍历, inorder
是同一棵树的中序遍历,请构造二叉树并返回其根节点。
2. 解题思路
① 通过前序遍历序列的第一个节点可以得到待构造二叉树的根节点。
② 再通过中序遍历序列,由根节点将该序列分为左右两个子树。
③ 递归构建子树。
preorder | |-----------------------| |--------------------|
preL preL+1 rootIndex-inL+preL rootIndex-inL+preL+1 preR
inorder |--------------------| | |--------------------|
inL rootIndex-1 rootIndex rootIndex+1 inR
3. 实现代码
DFS 中四个 int 类型参数
① preL:前序遍历的起点
② preR:前序遍历的重点
③ inL:中序遍历的起点
④ inR:中序遍历的终点
/**
* 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 {
HashMap<Integer, Integer> map;
private TreeNode DFS(int[] preorder, int[] inorder, int preL, int preR, int inL, int inR) {
if (preL > preR) return null;
TreeNode root = new TreeNode(preorder[preL]);
// 根节点在中序遍历中的下标
int rootIndex = map.get(preorder[preL]);
int lenLeft = rootIndex - inL;
root.left = DFS(preorder, inorder, preL + 1, lenLeft + preL, inL, rootIndex - 1);
root.right = DFS(preorder, inorder, lenLeft + preL + 1, preR, rootIndex + 1, inR);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
int len = preorder.length;
map = new HashMap<>();
for (int i = 0; i < len; i++) {
map.put(inorder[i], i);
}
return DFS(preorder, inorder, 0, len - 1, 0, len - 1);
}
}