Skip to content

Commit 1f35002

Browse files
committed
添加105题Java代码
只看到106题的代码,添加了105题的代码,顺便加了“106.从中序与后序遍历序列构造二叉树”这句好辨别,没什么问题吧 :D
1 parent c356a0c commit 1f35002

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

problems/0106.从中序与后序遍历序列构造二叉树.md

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -580,8 +580,10 @@ tree2 的前序遍历是[1 2 3], 后序遍历是[3 2 1]。
580580
581581
## 其他语言版本
582582
583-
584583
Java:
584+
585+
106.从中序与后序遍历序列构造二叉树
586+
585587
```java
586588
class Solution {
587589
public TreeNode buildTree(int[] inorder, int[] postorder) {
@@ -617,8 +619,43 @@ class Solution {
617619
}
618620
```
619621

622+
105.从前序与中序遍历序列构造二叉树
623+
624+
```java
625+
class Solution {
626+
public TreeNode buildTree(int[] preorder, int[] inorder) {
627+
return helper(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
628+
}
629+
630+
public TreeNode helper(int[] preorder, int preLeft, int preRight,
631+
int[] inorder, int inLeft, int inRight) {
632+
// 递归终止条件
633+
if (inLeft > inRight || preLeft > preRight) return null;
634+
635+
// val 为前序遍历第一个的值,也即是根节点的值
636+
// idx 为根据根节点的值来找中序遍历的下标
637+
int idx = inLeft, val = preorder[preLeft];
638+
TreeNode root = new TreeNode(val);
639+
for (int i = inLeft; i <= inRight; i++) {
640+
if (inorder[i] == val) {
641+
idx = i;
642+
break;
643+
}
644+
}
645+
646+
// 根据 idx 来递归找左右子树
647+
root.left = helper(preorder, preLeft + 1, preLeft + (idx - inLeft),
648+
inorder, inLeft, idx - 1);
649+
root.right = helper(preorder, preLeft + (idx - inLeft) + 1, preRight,
650+
inorder, idx + 1, inRight);
651+
return root;
652+
}
653+
}
654+
```
655+
620656
Python:
621657
105.从前序与中序遍历序列构造二叉树
658+
622659
```python
623660
# Definition for a binary tree node.
624661
# class TreeNode:
@@ -637,6 +674,7 @@ class Solution:
637674
return root
638675
```
639676
106.从中序与后序遍历序列构造二叉树
677+
640678
```python
641679
# Definition for a binary tree node.
642680
# class TreeNode:

0 commit comments

Comments
 (0)