来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。

解答

通过中序遍历数组和后序遍历数组得到二叉树:

  1. 原理跟 38 题一致
  2. 后序遍历数组 pop 用于初始化节点,中序遍历数组用于判断是否有子树

    1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val, left, right) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.left = (left===undefined ? null : left)
    6. * this.right = (right===undefined ? null : right)
    7. * }
    8. */
    9. /**
    10. * @param {number[]} inorder
    11. * @param {number[]} postorder
    12. * @return {TreeNode}
    13. */
    14. var buildTree = function(inorder, postorder) {
    15. if (inorder.length && postorder.length) {
    16. const rootVal = postorder.pop();
    17. const rootIndex = inorder.indexOf(rootVal);
    18. const root = new TreeNode(rootVal);
    19. root.right = buildTree(
    20. inorder.slice(rootIndex + 1),
    21. postorder
    22. );
    23. root.left = buildTree(
    24. inorder.slice(0, rootIndex),
    25. postorder
    26. );
    27. return root;
    28. } else {
    29. return null;
    30. }
    31. };