LeetCode 0106. Construct Binary Tree from Inorder and Postorder Traversal Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0106. Construct Binary Tree from Inorder and Postorder Traversal

Description

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:

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.

Solutions

Solution 1: Hash Table + Recursion

The last node in the post-order traversal is the root node. We can find the position of the root node in the in-order traversal, and then recursively construct the left and right subtrees.

Specifically, we first use a hash table d to store the position of each node in the in-order traversal. Then we design a recursive function dfs(i, j, n), where i and j represent the starting positions of the in-order and post-order traversals, respectively, and n represents the number of nodes in the subtree. The function logic is as follows:

  • If n ≤ 0, it means the subtree is empty, return a null node.
  • Otherwise, take out the last node v of the post-order traversal, and then find the position k of v in the in-order traversal using the hash table d. Then the number of nodes in the left subtree is k - i, and the number of nodes in the right subtree is n - k + i - 1.
  • Recursively construct the left subtree dfs(i, j, k - i) and the right subtree dfs(k + 1, j + k - i, n - k + i - 1), connect them to the root node, and finally return the root node.

The time complexity is O(n), and the space complexity is O(n). Here, n is the number of nodes in the binary tree.

PythonJavaC++GoTypeScriptRust
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]: def dfs(i: int, j: int, n: int) -> Optional[TreeNode]: if n <= 0: return None v = postorder[j + n - 1] k = d[v] l = dfs(i, j, k - i) r = dfs(k + 1, j + k - i, n - k + i - 1) return TreeNode(v, l, r) d = {v: i for i, v in enumerate(inorder)} return dfs(0, 0, len(inorder))(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !