从中序与后序遍历序列构造二叉树
给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。
示例 1:
输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]
1
2
2
/**
* 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[]} inorder
* @param {number[]} postorder
* @return {TreeNode}
*/
var buildTree = function(inorder, postorder) {
if(!postorder.length) return null
let rootIndex = postorder.length - 1
let rootVal = postorder[rootIndex]
let root = new TreeNode(rootVal)
let centerl = inorder.slice(0, inorder.indexOf(rootVal))
let centerr = inorder.slice(inorder.indexOf(rootVal) + 1)
let afterl = postorder.slice(0, inorder.indexOf(rootVal))
let afterr = postorder.slice(inorder.indexOf(rootVal), rootIndex)
root.left = buildTree(centerl, afterl)
root.right = buildTree(centerr, afterr)
return root
};
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
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
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal