diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index cfd22288..cfc50c7b 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -580,8 +580,10 @@ tree2 的前序遍历是[1 2 3], 后序遍历是[3 2 1]。 ## 其他语言版本 - Java: + +106.从中序与后序遍历序列构造二叉树 + ```java class Solution { 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: 105.从前序与中序遍历序列构造二叉树 + ```python # Definition for a binary tree node. # class TreeNode: @@ -637,6 +674,7 @@ class Solution: return root ``` 106.从中序与后序遍历序列构造二叉树 + ```python # Definition for a binary tree node. # class TreeNode: