mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
添加105题Java代码
只看到106题的代码,添加了105题的代码,顺便加了“106.从中序与后序遍历序列构造二叉树”这句好辨别,没什么问题吧 :D
This commit is contained in:
@ -580,8 +580,10 @@ tree2 的前序遍历是[1 2 3], 后序遍历是[3 2 1]。
|
|||||||
|
|
||||||
## 其他语言版本
|
## 其他语言版本
|
||||||
|
|
||||||
|
|
||||||
Java:
|
Java:
|
||||||
|
|
||||||
|
106.从中序与后序遍历序列构造二叉树
|
||||||
|
|
||||||
```java
|
```java
|
||||||
class Solution {
|
class Solution {
|
||||||
public TreeNode buildTree(int[] inorder, int[] postorder) {
|
public TreeNode buildTree(int[] inorder, int[] postorder) {
|
||||||
@ -617,8 +619,43 @@ class Solution {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
105.从前序与中序遍历序列构造二叉树
|
||||||
|
|
||||||
|
```java
|
||||||
|
class Solution {
|
||||||
|
public TreeNode buildTree(int[] preorder, int[] inorder) {
|
||||||
|
return helper(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
public TreeNode helper(int[] preorder, int preLeft, int preRight,
|
||||||
|
int[] inorder, int inLeft, int inRight) {
|
||||||
|
// 递归终止条件
|
||||||
|
if (inLeft > inRight || preLeft > preRight) return null;
|
||||||
|
|
||||||
|
// val 为前序遍历第一个的值,也即是根节点的值
|
||||||
|
// idx 为根据根节点的值来找中序遍历的下标
|
||||||
|
int idx = inLeft, val = preorder[preLeft];
|
||||||
|
TreeNode root = new TreeNode(val);
|
||||||
|
for (int i = inLeft; i <= inRight; i++) {
|
||||||
|
if (inorder[i] == val) {
|
||||||
|
idx = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根据 idx 来递归找左右子树
|
||||||
|
root.left = helper(preorder, preLeft + 1, preLeft + (idx - inLeft),
|
||||||
|
inorder, inLeft, idx - 1);
|
||||||
|
root.right = helper(preorder, preLeft + (idx - inLeft) + 1, preRight,
|
||||||
|
inorder, idx + 1, inRight);
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
105.从前序与中序遍历序列构造二叉树
|
105.从前序与中序遍历序列构造二叉树
|
||||||
|
|
||||||
```python
|
```python
|
||||||
# Definition for a binary tree node.
|
# Definition for a binary tree node.
|
||||||
# class TreeNode:
|
# class TreeNode:
|
||||||
@ -637,6 +674,7 @@ class Solution:
|
|||||||
return root
|
return root
|
||||||
```
|
```
|
||||||
106.从中序与后序遍历序列构造二叉树
|
106.从中序与后序遍历序列构造二叉树
|
||||||
|
|
||||||
```python
|
```python
|
||||||
# Definition for a binary tree node.
|
# Definition for a binary tree node.
|
||||||
# class TreeNode:
|
# class TreeNode:
|
||||||
|
Reference in New Issue
Block a user