@@ -580,8 +580,10 @@ tree2 的前序遍历是[1 2 3], 后序遍历是[3 2 1]。
580
580
581
581
## 其他语言版本
582
582
583
-
584
583
Java:
584
+
585
+ 106.从中序与后序遍历序列构造二叉树
586
+
585
587
```java
586
588
class Solution {
587
589
public TreeNode buildTree(int[] inorder, int[] postorder) {
@@ -617,8 +619,43 @@ class Solution {
617
619
}
618
620
```
619
621
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
+
620
656
Python:
621
657
105.从前序与中序遍历序列构造二叉树
658
+
622
659
``` python
623
660
# Definition for a binary tree node.
624
661
# class TreeNode:
@@ -637,6 +674,7 @@ class Solution:
637
674
return root
638
675
```
639
676
106.从中序与后序遍历序列构造二叉树
677
+
640
678
``` python
641
679
# Definition for a binary tree node.
642
680
# class TreeNode:
0 commit comments