105 从前序与中序遍历序列构造二叉树
01
/**
* 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) {
return subTree(preorder,inorder,0,inorder.length-1,0,preorder.length-1);
}
public TreeNode subTree(int[] pre,int[] vin,int start,int end,int k,int p_end){
if(k>p_end || start>end){
return null;
}
TreeNode root=new TreeNode(pre[k]);
int i=start;
for(;i<=end;i++){
if(vin[i]==pre[k]){
break;
}
}
//左子树
if(i==start){
root.left=null;
}else{
root.left=subTree(pre,vin,start,i-1,k+1,k+i-start);
}
//右子树
if(i==end){
root.right=null;
}else{
root.right=subTree(pre,vin,i+1,end,k+i-start+1,p_end);
}
return root;
}
}
hashmap
/**
* 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 {
private Map<Integer,Integer> map;
public TreeNode buildTree(int[] preorder, int[] inorder) {
map=new HashMap<>();
for (int i=0;i<inorder.length;i++){
map.put(inorder[i],i);
}
return subTree(preorder,inorder,0,inorder.length-1,0,preorder.length-1);
}
public TreeNode subTree(int[] pre,int[] vin,int start,int end,int k,int p_end){
if(k>p_end || start>end){
return null;
}
TreeNode root=new TreeNode(pre[k]);
int i=map.get(pre[k]);
// for(;i<=end;i++){
// if(vin[i]==pre[k]){
// break;
// }
// }
//左子树
if(i==start){
root.left=null;
}else{
root.left=subTree(pre,vin,start,i-1,k+1,k+i-start);
}
//右子树
if(i==end){
root.right=null;
}else{
root.right=subTree(pre,vin,i+1,end,k+i-start+1,p_end);
}
return root;
}
}
时间复杂度
O
(
n
)
O(n)
O(n),
n
n
n是树中的节点个数。
空间复杂度
O
(
n
)
O(n)
O(n),哈希表。