# 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 inorderTraversal(self, root: Optional[TreeNode]) -> List[int]: stack, rst = [root], [] while stack: i = stack.pop() if isinstance(i, TreeNode): stack.extend([i.right, i.val, i.left]) elif isinstance(i, int): rst.append(i) return rst
注 : Optional[] -> Optional[int] == Optional[int, None]
防止在传入参数为None时进行报错
2. 开始经典两数之和
# 直接拷贝最easy的方法 class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: hashtable = dict() for i, num in enumerate(nums): if target - num in hashtable: return[hashtable[target-num], i] hashtable[num] = i return []