- 二叉树开始 使用Python3 完成前中后序遍历
点击查看代码
# 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 []
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/289729.html