2019-11-02 12:07:41 +08:00
|
|
|
|
# 7. 重建二叉树
|
|
|
|
|
|
|
|
|
|
[NowCoder](https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6?tpId=13&tqId=11157&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
|
|
|
|
|
|
|
|
|
## 题目描述
|
|
|
|
|
|
|
|
|
|
根据二叉树的前序遍历和中序遍历的结果,重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
|
|
|
|
|
|
|
|
|
|
|
2019-11-02 17:33:10 +08:00
|
|
|
|
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/31d9adce-2af8-4754-8386-0aabb4e500b0.png" width="300"/> </div><br>
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
|
|
|
|
## 解题思路
|
|
|
|
|
|
|
|
|
|
前序遍历的第一个值为根节点的值,使用这个值将中序遍历结果分成两部分,左部分为树的左子树中序遍历结果,右部分为树的右子树中序遍历的结果。
|
|
|
|
|
|
2019-11-02 17:33:10 +08:00
|
|
|
|
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/c269e362-1128-4212-9cf3-d4c12b363b2f.gif" width="330px"> </div><br>
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
// 缓存中序遍历数组每个值对应的索引
|
|
|
|
|
private Map<Integer, Integer> indexForInOrders = new HashMap<>();
|
|
|
|
|
|
|
|
|
|
public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
|
|
|
|
|
for (int i = 0; i < in.length; i++)
|
|
|
|
|
indexForInOrders.put(in[i], i);
|
|
|
|
|
return reConstructBinaryTree(pre, 0, pre.length - 1, 0);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private TreeNode reConstructBinaryTree(int[] pre, int preL, int preR, int inL) {
|
|
|
|
|
if (preL > preR)
|
|
|
|
|
return null;
|
|
|
|
|
TreeNode root = new TreeNode(pre[preL]);
|
|
|
|
|
int inIndex = indexForInOrders.get(root.val);
|
|
|
|
|
int leftTreeSize = inIndex - inL;
|
|
|
|
|
root.left = reConstructBinaryTree(pre, preL + 1, preL + leftTreeSize, inL);
|
|
|
|
|
root.right = reConstructBinaryTree(pre, preL + leftTreeSize + 1, preR, inL + leftTreeSize + 1);
|
|
|
|
|
return root;
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2019-11-02 17:33:10 +08:00
|
|
|
|
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>
|