【LeetCode】 105. Construct Binary Tree from Preorder and Inorder Traversal
Description
Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.
給兩個整數數列前序和中序,分別是對同一棵二元樹的前序遍歷和中序遍歷,請根據前序和中序建立並回傳這棵二元樹。
Example:

Solution
- 關於何謂二元樹、前序、中序若不懂的人可以參考我的資料結構筆記。
- 本題的解題思路主要是利用遞迴,將每個節點都當作是子問題去解決。
- 由前序可以知道哪個節點在上面(越前面的越上面)、而中序可以知道哪個節點靠左(越前面的越左邊)
- 因此我們可以知道前序的第一個元素一定是 root 的值,且該元素對應到中序後,左邊的值就在左邊,右邊的值就在右邊。
- 接著就將 left 和 right 分別當作新的 root node 下去做即可。
- 遞迴的中止條件是在 inorder 中找不到對應元素
Code