|
|
|
---
|
|
|
|
二叉树相关
|
|
|
|
---
|
|
|
|
|
|
|
|
#### 目录
|
|
|
|
|
|
|
|
1. #### [07. 重建二叉树](https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/)
|
|
|
|
|
|
|
|
#### [07. 重建二叉树](https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/)
|
|
|
|
|
|
|
|
```java
|
|
|
|
class Solution {
|
|
|
|
|
|
|
|
public TreeNode buildTree(int[] preorder, int[] inorder) {
|
|
|
|
int n = preorder.length;
|
|
|
|
if (n == 0) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
int rootVal = preorder[0], rootIndex = 0;
|
|
|
|
for (int i = 0; i < n; i++) {
|
|
|
|
if (inorder[i] == rootVal) {
|
|
|
|
rootIndex = i;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
TreeNode root = new TreeNode(rootVal);
|
|
|
|
root.left = buildTree(Arrays.copyOfRange(preorder, 1, 1 + rootIndex),
|
|
|
|
Arrays.copyOfRange(inorder, 0, rootIndex));
|
|
|
|
root.right = buildTree(Arrays.copyOfRange(preorder, 1 + rootIndex, n),
|
|
|
|
Arrays.copyOfRange(inorder, rootIndex + 1, n));
|
|
|
|
return root;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
```java
|
|
|
|
class Solution {
|
|
|
|
|
|
|
|
public TreeNode buildTree(int[] preorder, int[] inorder) {
|
|
|
|
if (preorder == null || preorder.length == 0) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
TreeNode root = new TreeNode(preorder[0]);
|
|
|
|
int length = preorder.length;
|
|
|
|
Stack<TreeNode> stack = new Stack<>();
|
|
|
|
stack.push(root);
|
|
|
|
int inorderIndex = 0;
|
|
|
|
for (int i = 1; i < length; i++) {
|
|
|
|
int preorderVal = preorder[i];
|
|
|
|
TreeNode node = stack.peek();
|
|
|
|
if (node.val != inorder[inorderIndex]) {
|
|
|
|
node.left = new TreeNode(preorderVal);
|
|
|
|
stack.push(node.left);
|
|
|
|
} else {
|
|
|
|
while (!stack.isEmpty() && stack.peek().val == inorder[inorderIndex]) {
|
|
|
|
node = stack.pop();
|
|
|
|
inorderIndex++;
|
|
|
|
}
|
|
|
|
node.right = new TreeNode(preorderVal);
|
|
|
|
stack.push(node.right);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return root;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|