# LeetCode题库解答与分析——#106. 从中序与后序遍历序列构造二叉树ConstructBinaryTreeFromInorderAndPostorderTraversal

中序遍历 = [9,3,15,20,7]

    3
/ \
9  20
/  \
15   7

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
/ \
9  20
/  \
15   7

/**
* Definition for a binary tree node.
* function TreeNode(val) {
*     this.val = val;
*     this.left = this.right = null;
* }
*/
/**
* @param {number[]} inorder
* @param {number[]} postorder
* @return {TreeNode}
*/
var buildTree = function(inorder, postorder) {
var l=postorder.length;
if(l==0){
return null;
}
var root=new TreeNode(postorder[l-1]);
if(l==1){
return root;
}
var pos=0;
for(pos=0;pos<l;pos++){
if(inorder[pos]==postorder[l-1]){
break;
}
}
var Lpostorder=new Array(pos);
var Linorder=new Array(pos);
var Rpostorder=new Array(l-pos-1);
var Rinorder=new Array(l-pos-1);
for(var i=0;i<pos;i++){
Linorder[i]=inorder[i+1];
Lpostorder[i]=postorder[i];
}
root.left=buildTree(Linorder,Lpostorder);
for(var i=0;i<l-pos-1;i++){
Rinorder[i]=inorder[i+pos+1];
Rpostorder[i]=postorder[i+pos];
}
root.right=buildTree(Rinorder,Rpostorder);
return root;

};

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120