106. 从中序与后序遍历序列构造二叉树(JS实现)

1 题目

根据一棵树的中序遍历与后序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/
9 20
/
15 7

2 思路

这道题的主要思路跟从中序和前序序列构造二叉树,只不过前序换成了后序,我们就需要先构造右子树,再构造左子树

3代码

/**
 * 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) {
function d(pArr, inArr, begin, end) {
    if (begin > end) return null;

    let nodeValuie = pArr.pop();
    let index = inArr.indexOf(nodeValuie);
    let node = new TreeNode(nodeValuie);

    node.right = d(pArr, inArr, index + 1, end);
    node.left = d(pArr, inArr, begin, index - 1);

    return node;
  }

  return d(postorder, inorder, 0, inorder.length - 1);


  function TreeNode(val) {
    this.val = val;
    this.left = this.right = null;
  }
};

猜你喜欢

转载自blog.csdn.net/zjw_python/article/details/107029176