难度中等1554收藏分享切换为英文接收动态反馈
给定两个整数数组 preorder
和 inorder
,其中 preorder
是二叉树的先序遍历, inorder
是同一棵树的中序遍历,请构造二叉树并返回其根节点。
示例 1:
输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] 输出: [3,9,20,null,null,15,7]
示例 2:
输入: preorder = [-1], inorder = [-1] 输出: [-1]
提示:
1 <= preorder.length <= 3000
inorder.length == preorder.length
-3000 <= preorder[i], inorder[i] <= 3000
preorder
和inorder
均 无重复 元素inorder
均出现在preorder
preorder
保证 为二叉树的前序遍历序列inorder
保证 为二叉树的中序遍历序列
/**
* 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) {
int n = preorder.length;
return myBuildTree(inorder,0,n - 1, preorder,0,n - 1);
}
public TreeNode myBuildTree(int [] inorder, int inleft,int inright,int [] preorder,int preleft,int preright) {
if(inleft > inright) {
return null;
}
TreeNode root = new TreeNode(preorder[preleft]);
int inroot = -1;
for(int i = inleft; i <= inright; i++) {
if(inorder[i] == preorder[preleft]) {
inroot = i;
break;
}
}
root.left = myBuildTree(inorder,inleft,inroot - 1,preorder,preleft + 1,inroot - inleft + preleft);
root.right = myBuildTree(inorder,inroot + 1, inright,preorder,preright - (inright - inroot - 1) ,preright);
return root;
}
}