Skip to content

Commit 74cb27f

Browse files
authored
Update 0106.从中序与后序遍历序列构造二叉树.md
优化js版本代码并添加注释说明
1 parent 3d303eb commit 74cb27f

File tree

1 file changed

+14
-17
lines changed

1 file changed

+14
-17
lines changed

problems/0106.从中序与后序遍历序列构造二叉树.md

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -792,30 +792,27 @@ func findRootIndex(target int,inorder []int) int{
792792

793793
```javascript
794794
var buildTree = function(inorder, postorder) {
795-
if (!postorder.length) return null
796-
797-
let root = new TreeNode(postorder[postorder.length - 1])
798-
799-
let index = inorder.findIndex(number => number === root.val)
800-
801-
root.left = buildTree(inorder.slice(0, index), postorder.slice(0, index))
802-
root.right = buildTree(inorder.slice(index + 1, inorder.length), postorder.slice(index, postorder.length - 1))
803-
804-
return root
795+
if (!preorder.length) return null;
796+
const rootVal = postorder.pop(); // 从后序遍历的数组中获取中间节点的值, 即数组最后一个值
797+
let rootIndex = inorder.indexOf(rootVal); // 获取中间节点在中序遍历中的下标
798+
const root = new TreeNode(rootVal); // 创建中间节点
799+
root.left = buildTree(inorder.slice(0, rootIndex), postorder.slice(0, rootIndex)); // 创建左节点
800+
root.right = buildTree(inorder.slice(rootIndex + 1), postorder.slice(rootIndex)); // 创建右节点
801+
return root;
805802
};
806803
```
807804

808805
从前序与中序遍历序列构造二叉树
809806

810807
```javascript
811808
var buildTree = function(preorder, inorder) {
812-
if(!preorder.length)
813-
return null;
814-
let root = new TreeNode(preorder[0]);
815-
let mid = inorder.findIndex((number) => number === root.val);
816-
root.left = buildTree(preorder.slice(1, mid + 1), inorder.slice(0, mid));
817-
root.right = buildTree(preorder.slice(mid + 1, preorder.length), inorder.slice(mid + 1, inorder.length));
818-
return root;
809+
if (!preorder.length) return null;
810+
const rootVal = preorder.shift(); // 从前序遍历的数组中获取中间节点的值, 即数组第一个值
811+
const index = inorder.indexOf(rootVal); // 获取中间节点在中序遍历中的下标
812+
const root = new TreeNode(rootVal); // 创建中间节点
813+
root.left = buildTree(preorder.slice(0, index), inorder.slice(0, index)); // 创建左节点
814+
root.right = buildTree(preorder.slice(index), inorder.slice(index + 1)); // 创建右节点
815+
return root;
819816
};
820817
```
821818

0 commit comments

Comments
 (0)