剑指Offer-Javascript版-重建二叉树

对应LeetCode上的题目:面试题07. 重建二叉树

题目描述:输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

例子

1
2
3
4
5
6
7
8
9
10
11
给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]

返回如下的二叉树:

3
/ \
9 20
/ \
15 7

解法:二叉树的前序遍历和中序遍历

二叉树的前序遍历中,第一个数字是二叉树的根节点。在中序遍历中,根节点位于序列的中间,即根节点的左边是左子树节点的值,右边是右子树节点的值。

由前序遍历 [3,9,20,15,7] 可知,3 是根节点。中序遍历 [9,3,15,20,7] 可知,根节点 3 的左边是左子树节点 9,右边是右子树节点 15207。所以

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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/

var buildTree = function(preorder, inorder) {
if(!preorder.length || !inorder.length) {
return null
}

const rootVal = preorder[0]
const node = new TreeNode(rootVal)

// i有两个含义,一个是根节点在中序遍历结果中的下标, 另一个是当前左子树的节点个数
let i = 0;
for(; i < inorder.length; ++i) {
if(inorder[i] === rootVal) {
break;
}
}

// i主要是求出根节点在中序遍历序列中的位置。那么i位置前面的都是左子树的值,后边的都是右子树的值。
// 中序遍历和前序遍历的左子树和右子树节点的个数都分别相等
node.left = buildTree(preorder.slice(1, i+1), inorder.slice(0, i))
node.right = buildTree(preorder.slice(i+1), inorder.slice(i + 1))

return node
};

知识扩展

You forgot to set the business and currency_code for Paypal. Please set it in _config.yml.
You forgot to set the url Patreon. Please set it in _config.yml.
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×