[LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal_Medium tag: Tree Traversal
2018-07-24 04:11 Johnson_强生仔仔 阅读(315) 评论(0) 收藏 举报Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7] inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
这个题目的思路就是利用preorder 和inorder的两种特性, 我们可以发现, preorder[0] 总是root, 然后inorder 里面根据之前的root, 可以将inorder分为left tree和right tree,
然后return root, recursive call即可.
1. Constraints
1) pre or in can be empty
2. ideas
recursively DFS, 分别得到root, root.left & root.right, 返回root
3. Code
class Solution: def constructBT(self, preorder, inorder): if not preorder or not inorder: return #note 别忘了not before inorder root, index = TreeNode(preorder[0]), inorder.index(preorder[0]) root.left = self.constructBT(preorder[1:1+index], inorder[:index]) root.right = self.constructBT(preorder[1+index:], inorder[index+1:]) return root
4. Test cases
1) edge case
2)
preorder = [3,9,20,15,7] inorder = [9,3,15,20,7]
5. Complexity:Python index + slicing 版本
设 n 为节点总数,h 为树高。以下结论针对上面的 .index() 查找和数组切片实现。
Time Complexity:最坏 O(n²)。 每层 .index() 线性查找根位置,同时切片会复制数组。树退化成链时,处理长度依次约为 n、n−1、…、1,总成本为 O(n²)。平衡树情况下为 O(n log n)。
Space Complexity:最坏 O(n²),即使不包含返回的树。 递归栈本身为 O(h),最坏 O(n);但父调用的数组不会在子调用返回前释放。退化链上同时保留的切片长度累加为 n + (n−1) + … + 1,因此辅助空间最坏为 O(n²)。返回的树另外占 O(n),不改变总空间的最坏 O(n²) 上界。平衡树时,沿递归路径的切片大小按比例递减,辅助空间为 O(n)。
注意:不能将递归栈 O(h) 直接当作本实现的全部辅助空间。若用哈希表记录 inorder 位置,并传索引区间避免切片,可以做到平均 O(n) 时间、O(n) 辅助空间。
复杂度补充根据本次学习讨论整理,AI辅助校对。
浙公网安备 33010602011771号