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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {number[]} preorder
* @param {number[]} inorder
* @return {TreeNode}
*/
var buildTree = function (preorder, inorder) {
// 前序 preorder
// 中序 inorder
// preorder的头节点就是root节点
// 然后在inorder里面找到这个节点
// 左边长度就是左子树个数
// 右边长度就是右子树个数
// preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
if (!preorder.length) return null;
const nodeValue = preorder[0];
const root = new TreeNode(nodeValue);
const idx = inorder.indexOf(nodeValue);

const leftLen = idx === -1 ? 0 : idx;
// const rightLen = ~idx ? inorder.length : inorder.length - idx - 1;
// console.log(idx, leftLen, 'xx')
// return
root.left = buildTree(
preorder.slice(1, 1 + leftLen),
inorder.slice(0, idx)
);
root.right = buildTree(
preorder.slice(1 + leftLen),
inorder.slice(idx + 1)
);
return root;
};

本站由 ao 使用 Stellar 1.29.1 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。