Algorithm
本周选择的算法题是:Construct Binary Tree from Preorder and Inorder Traversal
规则如下:
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
Solution
# 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, preorder: List[int], inorder: List[int]) -> TreeNode:
table = {}
for index, value in enumerate(inorder):
table[value] = index
def _recursive(pre_root_index, inorder_left, inorder_right) -> TreeNode:
if inorder_left > inorder_right: return None
root = TreeNode(preorder[pre_root_index])
inorder_index = table[root.val]
root.left = _recursive(pre_root_index+1, inorder_left, inorder_index-1)
root.right = _recursive(pre_root_index+inorder_index-inorder_left+1, inorder_index+1, inorder_right)
return root
return _recursive(0, 0, len(inorder)-1)
Review
Obj-C Optimization: IMP Cacheing Deluxe 作者有大量的底层优化经验,在此文章中分享了他关于 OC 方法调用的优化思路。
给我启发很大,附作者的优化金句:
对代码的优化越多,优化的收益就超大
— 收益递增原则
Tip
在 SwiftUI 里实现 TikTok 的 logo-ish 效果
Share
做了一张关于前端组件化规范的思维导图: