105. 从前序与中序遍历序列构造二叉树
题目描述
递归+map
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder == null || preorder.length == 0 || inorder == null || inorder.length == 0 || preorder.length != inorder.length) {
return null;
}
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < inorder.length; i++) {
map.put(inorder[i],i);
}
TreeNode res = buildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, map);
return res;
}
public TreeNode buildTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd, Map<Integer, Integer> map) {
if(preStart > preEnd || inStart > inEnd) {
return null;
}
TreeNode root = new TreeNode(preorder[preStart]);
//找到当前树的根节点,在中序遍历数组中存储的位置,将中序遍历分为左右子树的遍历序列
int rootInorderIndex = map.get(root.val);
//求出当前树的根节点的左子树的节点总数,便于在前序遍历的序列中,将当前根节点的左右子树遍历序列分开,便于分别创建当前根节点的左子树和右子树
int rootLeftTreeSum = rootInorderIndex - inStart;
root.left = buildTree(preorder, preStart + 1, preStart + rootLeftTreeSum, inorder, inStart, rootInorderIndex - 1, map);
root.right = buildTree(preorder, preStart + rootLeftTreeSum + 1, preEnd, inorder, rootInorderIndex + 1, inEnd,map);
return root;
}
}