本人新手为了面试互联网公司,将刷题做一个记录以及总结,方便之后学习!!
第5道问题 剑指offer 07 为一道中等题
力扣https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/
1.自己思考
二叉树的前序遍历,根节点->左节点->右节点,从中可以分析第一个3即为整个二叉树的根节点。
二叉树的中序遍历,左节点->根节点->右节点。
最后的输出是二叉树,由于之前对于二叉树的题目了解不多,直接参考答案。
对递归法答案进行分析:
1.利用hash表来进行映射,key设置为数组中元素的值,而value设置为下标。好处是能够降低每一步查找根节点的复杂度。
2.二叉树的核心思想简化来说,就是根节点,左节点,右节点。利用这个思想对整个二叉树进行分割,这也是迭代思想的由来。一步步递归直到叶子节点。
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
int n = preorder.length;
//构建一个存储下标的容器
HashMap<Integer,Integer> map = new HashMap<>();
for(int i=0;i<n;i++){
map.put(inorder[i],i);
}
//这里构建一个函数用来递归
TreeNode root= buildSubTree(preorder,inorder,0,n-1,0,n-1,map);
return root;
}
//函数含义:preorder_L/R 前序遍历中左右边界 inorder_L/R中序遍历边界
public TreeNode buildSubTree(int[] preorder,int[] inorder,int preorder_L,int preorder_R ,int inorder_L,int inorder_R, HashMap<Integer,Integer> map){
//递归的关键条件,退出条件
if(preorder_L>preorder_R){ //可以用前序遍历做退出条件,中序遍历也可以inorder_L>inorder_R
return null;
}
//找到根节点
int root_key = preorder[preorder_L];//map的键
int root_index = map.get(root_key);//中序遍历中
//计算左子树的长度
int len= root_index-inorder_L;
//构建根节点
TreeNode root = new TreeNode(root_key);
//左子树
root.left = buildSubTree(preorder, inorder, preorder_L+1, preorder_L+len, inorder_L, root_index-1,map);//均表示左子树的点
//右子树
root.right= buildSubTree(preorder, inorder, preorder_L+1+len, preorder_R, root_index+1, inorder_R,map);//两个数组的范围,很重要易错
return root;
}
}
结果:
总结:
1.二叉树构建,根节点,左节点,右节点三点很重要的因素。
2.熟练使用map,方便查找有利于简化编程。
3.递归思想的应用,退出条件要注意。
4.递归边界的问题,也就是本题中左子树,右子树的覆盖范围。