From 1f350021e36b5abd3602d556331b9f0b6092d29a Mon Sep 17 00:00:00 2001 From: hk27xing <244798299@qq.com> Date: Sun, 23 May 2021 23:12:09 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0105=E9=A2=98Java=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 只看到106题的代码,添加了105题的代码,顺便加了“106.从中序与后序遍历序列构造二叉树”这句好辨别,没什么问题吧 :D --- ...序与后序遍历序列构造二叉树.md | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) 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: