方法一:递归 算法思想:递归 ,中序遍历和前序遍历特点。
根节点先定义,左右子树参数式子是关键
左子树三个参数:先序根索引+1(先序特点中左右,子树也要考虑到),中序左边界in_left(定义好的),中序右边界i-1(中序直接切开就是)
右子树三个参数:先序根索引+左子树长度(中序计算得出)+1(因为先序右子树根是紧接着左子树最后一个的),中序左边界i+(中序直接切开),中序右边界in_right(定义好的) 时间复杂度:O(N),for循环遍历O(N) 空间复杂度: HashMap 使用 O(N)额外空间;递归操作中系统需使用 O(N) 额外空间。 终止条件:left>right 先判断 补充知识:定义树节点 值,左右。 inorder.length没有括号,哈希表提升搜索效率。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int preorder[]; //全局变量
Map<Integer,Integer>m =new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
this.preorder=preorder; //复制一份
for(int i=0;i<inorder.length;i++){
m.put(inorder[i],i); //哈希映射
}
return rec(0,0,inorder.length-1); //递归初始 ,先序,中左,中右
}
public TreeNode rec(int pre_root,int in_left,int in_right){
if(in_left>in_right) return null; //先判
TreeNode root=new TreeNode(preorder[pre_root]); //先得根
int i=m.get(preorder[pre_root]); //先序根值,获得中序根索引
root.left=rec(pre_root+1,in_left,i-1);
root.right=rec(pre_root+(i-in_left)+1,i+1,in_right);
return root;
}
}