mirror of
https://github.com/CyC2018/Interview-Notebook.git
synced 2026-10-30 18:23:52 +00:00
Update 7. 重建二叉树.md
题目链接改为力扣中的对应题目,题目描述和代码按该题的接口调整。
This commit is contained in:
+8
-8
@@ -2,7 +2,7 @@
|
||||
|
||||
## 题目链接
|
||||
|
||||
[牛客网](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)
|
||||
[Leetcode](https://leetcode.cn/problems/zhong-jian-er-cha-shu-lcof/)
|
||||
|
||||
## 题目描述
|
||||
|
||||
@@ -22,20 +22,20 @@
|
||||
// 缓存中序遍历数组每个值对应的索引
|
||||
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);
|
||||
public TreeNode deduceTree(int[] preorder, int[] inorder) {
|
||||
for (int i = 0; i < inorder.length; i++)
|
||||
indexForInOrders.put(inorder[i], i);
|
||||
return deduceTree(preorder, 0, preorder.length - 1, 0);
|
||||
}
|
||||
|
||||
private TreeNode reConstructBinaryTree(int[] pre, int preL, int preR, int inL) {
|
||||
private TreeNode deduceTree(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);
|
||||
root.left = deduceTree(pre, preL + 1, preL + leftTreeSize, inL);
|
||||
root.right = deduceTree(pre, preL + leftTreeSize + 1, preR, inL + leftTreeSize + 1);
|
||||
return root;
|
||||
}
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user