编程语言
首页 > 编程语言> > leetcode杂交刷题之始 -- Python3

leetcode杂交刷题之始 -- Python3

作者:互联网

  1. 二叉树开始 使用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 []

标签:right,val,--,self,stack,int,num,leetcode,Python3
来源: https://www.cnblogs.com/DocGu/p/16698318.html