给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| var buildTree = function(inorder, postorder) { if (!inorder.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; };
|
上面的代码每层递归定义了新的数组,浪费了一些时间空间。
可以将新数组在原数组中的首尾下标代替新数组实体作为参数在递归中传递:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| var buildTree = function(inorder, postorder) { const build = (inLeft, inRight, postLeft, postRight) => { if (inLeft > inRight) return null; const rootVal = postorder[postRight]; const root = new TreeNode(rootVal); const rootIndex = inorder.indexOf(rootVal); const leftSize = rootIndex - inLeft; root.left = build(inLeft, rootIndex - 1, postLeft, postLeft + leftSize - 1); root.right = build(rootIndex + 1, inRight, postLeft + leftSize, postRight - 1); return root; }; return build(0, inorder.length - 1, 0, postorder.length - 1); };
|