From a0e346b02282ac515b8c453abce795eff2189519 Mon Sep 17 00:00:00 2001 From: Joshua <47053655+Joshua-Lu@users.noreply.github.com> Date: Fri, 14 May 2021 00:56:39 +0800 Subject: [PATCH] =?UTF-8?q?Update=200106.=E4=BB=8E=E4=B8=AD=E5=BA=8F?= =?UTF-8?q?=E4=B8=8E=E5=90=8E=E5=BA=8F=E9=81=8D=E5=8E=86=E5=BA=8F=E5=88=97?= =?UTF-8?q?=E6=9E=84=E9=80=A0=E4=BA=8C=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加 0106.从中序与后序遍历序列构造二叉树 Java版本 --- ...序与后序遍历序列构造二叉树.md | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index f1f30b71..5533a818 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -582,7 +582,41 @@ tree2 的前序遍历是[1 2 3], 后序遍历是[3 2 1]。 Java: +```java +class Solution { + public TreeNode buildTree(int[] inorder, int[] postorder) { + return buildTree1(inorder, 0, inorder.length, postorder, 0, postorder.length); + } + public TreeNode buildTree1(int[] inorder, int inLeft, int inRight, + int[] postorder, int postLeft, int postRight) { + // 没有元素了 + if (inRight - inLeft < 1) { + return null; + } + // 只有一个元素了 + if (inRight - inLeft == 1) { + return new TreeNode(inorder[inLeft]); + } + // 后序数组postorder里最后一个即为根结点 + int rootVal = postorder[postRight - 1]; + TreeNode root = new TreeNode(rootVal); + int rootIndex = 0; + // 根据根结点的值找到该值在中序数组inorder里的位置 + for (int i = inLeft; i < inRight; i++) { + if (inorder[i] == rootVal) { + rootIndex = i; + } + } + // 根据rootIndex划分左右子树 + root.left = buildTree1(inorder, inLeft, rootIndex, + postorder, postLeft, postLeft + (rootIndex - inLeft)); + root.right = buildTree1(inorder, rootIndex + 1, inRight, + postorder, postLeft + (rootIndex - inLeft), postRight - 1); + return root; + } +} +``` Python: