1、递归法:
递归法思维流程:
把中序遍历的值和对应索引组成一个map,前序遍历的第一个值为root,可根据这个root在中序遍历的map中找到root的index,由于中序遍历的特点,所以索引小于index的元素都在root的左子树中,索引大于index的元素都在右子树中,这时我们就可以通过更新递归参数的方式把这个树分为了两部分,利用返回根节点,我们通过控制参数分别对左右子树进行递归调用,返回了调用者的左右子节点,把左右插入root,这就是一个基本递归层次,再用参数控制递归的终点。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder==null||preorder.length==0){
return null;
}
Map<Integer,Integer> map = new HashMap<>();
for(int i=0;i<inorder.length;i++){
map.put(inorder[i],i);
}
return solve(preorder,0,preorder.length-1,inorder,0,inorder.length-1,map);
}
public TreeNode solve(int[] preorder,int preStart,int preEnd,int[] inorder,int inStart,int inEnd,Map<Integer,Integer> map){
if(preStart>preEnd){
return null;
}
TreeNode root = new TreeNode(preorder[preStart]);
if(preStart==preEnd){
return root;
}
int rootIndex = map.get(root.val);
int leftNodes = rootIndex -inStart,rightNodes = inEnd - rootIndex;
TreeNode left = solve(preorder,preStart+1,preStart+leftNodes,inorder,inStart,rootIndex-1,map);
TreeNode right = solve(preorder,preEnd-leftNodes,preEnd,inorder,rootIndex+1,inEnd,map);
root.left=left;
root.right=right;
return root;
}
}
2、迭代法
迭代思路:
这篇博客深入探讨了两种构建二叉树的方法——递归法和迭代法。递归法通过建立中序遍历的映射,找到根节点并将其划分为左右子树,进而递归构造整个树结构。而迭代法则使用栈来模拟递归过程,逐步构建树节点,同样实现了从预序和中序遍历恢复二叉树的功能。这两种方法对于理解数据结构和算法有重要的实践意义。
216

被折叠的 条评论
为什么被折叠?



