输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
示例 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]
解题思路:分治法
1、自己想的。。。
class Solution {
int[] preorder,inorder;
int index=0;
public TreeNode buildTree(int[] preorder, int[] inorder) {
this.preorder = preorder;
this.inorder = inorder;
return buildTreeHelper(0,preorder.length-1);
}
TreeNode buildTreeHelper(int start,int end){
if(start>end || index >= preorder.length) return null;
TreeNode root = new TreeNode(preorder[index]);
int rootIndex = serarch(inorder,preorder[index++]);
root.left = buildTreeHelper(start,rootIndex-1);
root.right = buildTreeHelper(rootIndex+1,end);
return root;
}
int serarch(int[] arr,int x){
int index=0;
while(arr[index]!=x) index++;
return index;
}
}
2、使用HashMap降低查找时间复杂度
class Solution {
int[] preorder,inorder;
int index=0;
HashMap<Integer,Integer> map;
public TreeNode buildTree(int[] preorder, int[] inorder) {
this.preorder = preorder;
this.inorder = inorder;
this.map = new HashMap<>();
for(int i=0;i<inorder.length;i++){
map.put(inorder[i],i);
}
return buildTreeHelper(0,preorder.length-1);
}
TreeNode buildTreeHelper(int start,int end){
if(start>end || index >= preorder.length) return null;
TreeNode root = new TreeNode(preorder[index]);
int rootIndex = map.get(preorder[index++]);
root.left = buildTreeHelper(start,rootIndex-1);
root.right = buildTreeHelper(rootIndex+1,end);
return root;
}
}
作者:Krahets
链接:https://leetcode.cn/leetbook/read/illustration-of-algorithm/99lxci/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。