输入一棵二叉树前序遍历和中序遍历的结果,请重建该二叉树。
注意:
- 二叉树中每个节点的值都互不相同;
- 输入的前序遍历和中序遍历一定合法;
数据范围
树中节点数量范围 [0,100][0,100]。样例
给定: 前序遍历是:[3, 9, 20, 15, 7] 中序遍历是:[9, 3, 15, 20, 7] 返回:[3, 9, 20, null, null, 15, 7, null, null, null, null] 返回的二叉树如下所示: 3 / \ 9 20 / \ 15 7
/**
* Definition for a binary tree node.
* class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Map<Integer, Integer> map = new HashMap<>();
int[] preorder;
public TreeNode buildTree(int[] preorder, int[] inorder) {
this.preorder = preorder;
int n = preorder.length;
if (n == 0) return null;
for (int i = 0; i < n; ++i)
map.put(inorder[i], i);
return dfs(0, 0, n - 1);
}
TreeNode dfs(int u, int l, int r) {
if (l > r) return null;
TreeNode node = new TreeNode(preorder[u]);
int t = map.get(preorder[u]);
node.left = dfs(u + 1, l, t - 1);
node.right = dfs(u + t - l + 1, t + 1, r);
return node;
}
}