From 74cb27fa2c8106fbcd6a25344ae474f81078f198 Mon Sep 17 00:00:00 2001 From: Junwen Huang Date: Sat, 23 Oct 2021 20:47:43 +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 优化js版本代码并添加注释说明 --- ...序与后序遍历序列构造二叉树.md | 31 +++++++++---------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/problems/0106.从中序与后序遍历序列构造二叉树.md b/problems/0106.从中序与后序遍历序列构造二叉树.md index a83341fd..11083a59 100644 --- a/problems/0106.从中序与后序遍历序列构造二叉树.md +++ b/problems/0106.从中序与后序遍历序列构造二叉树.md @@ -792,16 +792,13 @@ func findRootIndex(target int,inorder []int) int{ ```javascript var buildTree = function(inorder, postorder) { - if (!postorder.length) return null - - let root = new TreeNode(postorder[postorder.length - 1]) - - let index = inorder.findIndex(number => number === root.val) - - root.left = buildTree(inorder.slice(0, index), postorder.slice(0, index)) - root.right = buildTree(inorder.slice(index + 1, inorder.length), postorder.slice(index, postorder.length - 1)) - - return root + if (!preorder.length) return null; + const rootVal = postorder.pop(); // 从后序遍历的数组中获取中间节点的值, 即数组最后一个值 + let rootIndex = inorder.indexOf(rootVal); // 获取中间节点在中序遍历中的下标 + const root = new TreeNode(rootVal); // 创建中间节点 + root.left = buildTree(inorder.slice(0, rootIndex), postorder.slice(0, rootIndex)); // 创建左节点 + root.right = buildTree(inorder.slice(rootIndex + 1), postorder.slice(rootIndex)); // 创建右节点 + return root; }; ``` @@ -809,13 +806,13 @@ var buildTree = function(inorder, postorder) { ```javascript var buildTree = function(preorder, inorder) { - if(!preorder.length) - return null; - let root = new TreeNode(preorder[0]); - let mid = inorder.findIndex((number) => number === root.val); - root.left = buildTree(preorder.slice(1, mid + 1), inorder.slice(0, mid)); - root.right = buildTree(preorder.slice(mid + 1, preorder.length), inorder.slice(mid + 1, inorder.length)); - return root; + if (!preorder.length) return null; + const rootVal = preorder.shift(); // 从前序遍历的数组中获取中间节点的值, 即数组第一个值 + const index = inorder.indexOf(rootVal); // 获取中间节点在中序遍历中的下标 + const root = new TreeNode(rootVal); // 创建中间节点 + root.left = buildTree(preorder.slice(0, index), inorder.slice(0, index)); // 创建左节点 + root.right = buildTree(preorder.slice(index), inorder.slice(index + 1)); // 创建右节点 + return root; }; ```