输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
示例 1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
示例 2:
Input: preorder = [-1], inorder = [-1]
Output: [-1]
限制:
0 <= 节点个数 <= 5000
思路
本题主要用到了二叉树前序和中序遍历的特性,前序遍历,每次遍历,根节点一定在第一位,中序遍历,每次遍历,根节点一定在中间,能够划分左右子树,因此每次可以通过前序遍历的第一位,得知根节点的值,再从中序遍历的结果中找到根节点,从而划分左右子树
代码
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return build(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
}
public TreeNode build(int[] preorder, int s1, int e1, int[] inorder,int s2,int e2) {
if(s1>e1||s2>e2||s1>=preorder.length||s2>=inorder.length){
return null;
}
TreeNode root = new TreeNode(preorder[s1]);
int idx = s2;
int root_num = preorder[s1];
for(int i=s2;i<=e2;i++){
if(inorder[i]==root_num){
idx = i;
break;
}
}
int len1 = idx-1-s2;
int len2 = e2-idx-1;
root.left = build(preorder,s1+1,s1+idx-s2,inorder,s2,idx-1);
root.right = build(preorder,s1+idx-s2+1,e1,inorder,idx+1,e2);
return root;
}
}