力扣刷题时处理输入链表/二叉树和运行的函数(Python)

一些自己在力扣刷题时需要本地debug,处理输入、运行时用到的函数(Python)

from typing import List, Optional, Union, Tuple


# 力扣链表/二叉树空节点为null,替换成None
null = None

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

    def __str__(self):
        return f'{self.val}'

    def __repr__(self):
        return f'{self.val}'

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

    def __str__(self):
        return f'{self.val}'

    def __repr__(self):
        return f'{self.val}'
        
# 部分题目类名为Node,有的还有next属性
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next

# 常用,可根据力扣输入的列表输出二叉树
def create_treenodes_from_level(vals: List[int]) -> Optional[TreeNode]:
    """根据层序遍历结果(包含None)构建二叉树

    :param vals: List
    :return: TreeNode
    """
    if not vals:
        return None
    root = TreeNode(vals.pop(0))
    temp = [root]
    while vals:
        for i in range(len(temp)):
            node = temp.pop(0)
            if len(vals) >= 1:
                left_val = vals.pop(0)
                if left_val is not None:
                    node.left = TreeNode(left_val)
                    temp.append(node.left)
            if len(vals) >= 1:
                right_val = vals.pop(0)
                if right_val is not None:
                    node.right = TreeNode(right_val)
                    temp.append(node.right)
    return root

# 用来打印输出结果对比看
def level_traversal(root: TreeNode) -> List[List[int]]:
    """二叉树层序遍历

    :param root: TreeNode
    :return: List[List[int]]
    """
    if not root:
        return []
    res = [root]
    ans = []
    while res:
        l = len(res)
        temp = []
        for i in range(l):
            node = res.pop(0)
            temp.append(node.val)
            if node.left:
                res.append(node.left)
            if node.right:
                res.append(node.right)
        ans.append(temp)
    return ans

def create_listnodes(li: List[int]) -> Optional[ListNode]:
    """根据列表构建链表

    :param li: List[int]
    :return: ListNode
    """
    if not li:
        return
    head = ListNode(li[0])
    cur = head
    for i in range(1, len(li)):
        node = ListNode(li[i])
        cur.next = node
        cur = cur.next
    return head

def traversal_listnodes(head: ListNode) -> None:
    """遍历链表

    :param head: ListNode
    :return: None
    """
    while head:
        print(head.val,end=' ')
        head = head.next

if __name__ == '__main__':
	# 处理输入数据
    array = [4, -7, -3, null, null, -9, -3, 9, -7, -4, null, 6, null, -6, -6, null, null, 0, 6, 5, null, 9, null, null,
           -1, -4, null, null, null, -2]
    root = create_listnodes_from_level(array)
    print(level_traversal(root))
    
    # 执行普通类方法(类中只能有一个方法)
    s = Solution()
    method = getattr(s,dir(s)[-1])
    # 输入参数列表,二叉树/链表等就需要提前处理参数
    params = [root]
    res = method(*params)
    print(res)
    # 打印原地修改类型题目结果
    # print(params)
    
    # 执行创建对象/多次调用方法这类操作
    # commands = ["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
    # params = [[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
    # obj = eval(f'{commands[0]}(*{params[0]})')
    # for i in range(1,len(commands)):
    #     c = getattr(obj,commands[i])
    #     ret = c(*params[i])
    #     print(ret)

你可能感兴趣的:(链表,leetcode,python,数据结构)