Try   HackMD

106.Construct Binary Tree from Inorder and Postorder Traversal

tags: Medium,Tree,Array,Hash Table,Divide and Conquer

106. Construct Binary Tree from Inorder and Postorder Traversal

題目描述

Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.

範例

Example 1:

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]

Example 2:

Input: inorder = [-1], postorder = [-1]
Output: [-1]

Constraints:

  • 1 <= inorder.length <= 3000
  • postorder.length == inorder.length
  • -3000 <= inorder[i], postorder[i] <= 3000
  • inorder and postorder consist of unique values.
  • Each value of postorder also appears in inorder.
  • inorder is guaranteed to be the inorder traversal of the tree.
  • postorder is guaranteed to be the postorder traversal of the tree.

解答

Python

class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        idx_map = {val:idx for idx, val in enumerate(inorder)}

        def recur(low, high):
            if low > high:
                return

            idx = idx_map[postorder.pop()]
            
            root = TreeNode(inorder[idx])
            root.right = recur(idx + 1, high)
            root.left = recur(low, idx - 1)

            return root

        return recur(0, len(inorder) - 1)

Ron Chen Thu, Mar 16, 2023

Javascript

function buildTree(inorder, postorder) { const root = postorder[postorder.length - 1]; const rootIndex = inorder.indexOf(root); const leftInorder = inorder.slice(0, rootIndex); const rightInorder = inorder.slice(rootIndex + 1); const leftPostorder = postorder.slice(0, leftInorder.length); const rightPostorder = postorder.slice(leftInorder.length, postorder.length - 1); const tree = new TreeNode(root); if (leftInorder.length > 0) { tree.left = buildTree(leftInorder, leftPostorder); } if (rightInorder.length > 0) { tree.right = buildTree(rightInorder, rightPostorder); } return tree; }

MarsgoatMar 17, 2023

Reference

回到題目列表