[Golang][Leetcode][BinaryTree]刷題系列-105-Construct Binary Tree from Preorder and Inorder Traversal

Contents
105. Construct Binary Tree from Preorder and Inorder Traversal
Level : Medium
原題連結 : Click
題目 :
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 :
Note
Example 1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] Output: [3,9,20,null,null,15,7]
Example 2:
Input: preorder = [-1], inorder = [-1] Output: [-1]
解題思路 :
- 這題的概念可以直接參考 leetcode106題解,一樣是重構binary tree,只是這題使用到的資源是preorder & inorder
- 這題只是將106題postorder數組該成preorder數組,從原本取得最後一個數作為root改成取第一個數作為root
- 然後recursive code裡,切分的slice range改變,若理解了106題,那這題就可以輕鬆完成!
Recursive解法
- time complexity: O(n^2) , space complexity: O(n)
Runtime: 4 ms, faster than 91.79% of Go online submissions for Construct Binary Tree from Preorder and Inorder Traversal.
|
|
最後祝福努力認真的各位 “All your dream of are hidden in your daily life” 我們峰頂見!!!