// 递归法
class Solution {
private Map<Integer,Integer> indexMap = new HashMap<Integer,Integer>(); // 记录中序遍历的顺序
public TreeNode myBuildTree(int[] preorder, int[] inorder, int preLeft, int preRight, int inLeft, int inRight) {
if (preLeft > preRight) { //递归返回条件
return null;
}
TreeNode root = new TreeNode(preorder[preLeft]);
int rootLocation = indexMap.get(preorder[preLeft]); // 找到中序遍历下根节点的位置
int leftTreeLength = rootLocation - inLeft;
root.left = myBuildTree(preorder,inorder,preLeft +1,preLeft + leftTreeLength,inLeft, rootLocation-1); //递归进行下去的公式
root.right = myBuildTree(preorder,inorder,preLeft+leftTreeLength+1,preRight,rootLocation+1,inRight);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
int n = preorder.length;
for (int i = 0; i < n; i++) {
indexMap.put(inorder[i],i);
}
return myBuildTree(preorder,inorder,0,n-1,0,n-1);
}
}
// 迭代法(略)
剑指 Offer 07. 重建二叉树
最新推荐文章于 2022-03-09 17:07:57 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)