Medium草稿★★★★★O(n) 時間 · O(n) 空間
TreeDFSRecursionHashMap
Patterns🌳 樹形 DFS#️⃣ 雜湊
尚未複習過

解法已隱藏 — 先讀題目敘述、自己想想看,再點上方按鈕揭曉。

105Construct Binary Tree from Preorder and Inorder TraversalTreesMediumTrees

給定二元樹的前序遍歷和中序遍歷陣列,建構並回傳該二元樹。假設沒有重複值。

Example:

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

Intuition

TIP

前序的第一個元素是根;在中序中找到根的位置,左邊是左子樹、右邊是右子樹。

Approaches

1. Recursion + Linear Search — O(n^2) / O(n)
  • Idea: 每次遞迴從前序取根,在中序中線性搜尋根的位置來分割左右子樹
  • Time: O(n^2),每次搜尋根的位置需要 O(n)
  • Space: O(n)
class Solution {
    private var preIdx = 0

    fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? {
        preIdx = 0
        return build(preorder, inorder, 0, inorder.size - 1)
    }

    private fun build(preorder: IntArray, inorder: IntArray, inLeft: Int, inRight: Int): TreeNode? {
        if (inLeft > inRight) return null
        val rootVal = preorder[preIdx++]
        val root = TreeNode(rootVal)
        var inIdx = inLeft
        while (inorder[inIdx] != rootVal) inIdx++
        root.left = build(preorder, inorder, inLeft, inIdx - 1)
        root.right = build(preorder, inorder, inIdx + 1, inRight)
        return root
    }
}
⭐ 2. Recursion + HashMap — O(n) / O(n)
  • Idea: 預先建立中序值到索引的映射,將搜尋根位置的時間從 O(n) 降到 O(1)
  • Time: O(n)
  • Space: O(n)
class Solution {
    private var preIdx = 0
    private lateinit var inorderMap: HashMap<Int, Int>

    fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? {
        preIdx = 0
        inorderMap = HashMap()
        for (i in inorder.indices) {
            inorderMap[inorder[i]] = i
        }
        return build(preorder, 0, inorder.size - 1)
    }

    private fun build(preorder: IntArray, inLeft: Int, inRight: Int): TreeNode? {
        if (inLeft > inRight) return null
        val rootVal = preorder[preIdx++]
        val root = TreeNode(rootVal)
        val inIdx = inorderMap[rootVal]!!
        root.left = build(preorder, inLeft, inIdx - 1)
        root.right = build(preorder, inIdx + 1, inRight)
        return root
    }
}
Why build the left subtree before the right?

因為前序遍歷的順序是「根 -> 左 -> 右」。preIdx 是全域遞增的指標,建完根之後下一個元素必定屬於左子樹。如果先建右子樹會打亂順序。

🔑 Takeaways