leetcode本地调试:链表和二叉树,列表转链表,列表转二叉树,python

在本地调试leetcode上的链表和二叉树相关题目, 如pycharm,可以参考以下代码。



链表的本地调试

21. 合并两个有序链表 为例:

#定义节点
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

# 将传入的数组转化为链表
def create_linked_list(arr:List):
    head = ListNode(arr[0])
    cur = head
    for i in range(1, len(arr)):
        cur.next = ListNode(arr[i])
        cur = cur.next
    return head

# 传入链表头节点,以数组形式返回
def print_linked_list(head):
    cur = head
    res = []
    while cur:
        res.append(cur.val)
        cur = cur.next
    return res

class Solution():
    def mergeTwoLists(self, l1, l2):
        pre = ListNode(0)
        head = pre
        while l1 and l2:
            if l1.val >= l2.val:
                pre.next = l2
                l2 = l2.next
            else:
                pre.next = l1
                l1 = l1.next
            pre = pre.next
        pre.next = l1 if l1 else l2
        return head.next


if __name__ == "__main__":
	""" 链表debug """
	a = Solution()
    head1 = create_linked_list([1, 2, 4])
    head2 = create_linked_list([1, 3, 4])
    sorted_lists = a.mergeTwoLists(head1, head2)
    print(print_linked_list(sorted_lists))
	# 输出:[1, 1, 2, 3, 4, 4]

二叉树的本地调试

113. 路径总和 II 为例:

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


# 列表转二叉树
def List2Tree(l: List) -> TreeNode:
    """ 由输入列表生成树,返回根节点 """
    q = []
    if not l:
        return
    root = TreeNode(val=l.pop(0))
    q.append(root)
    while q:
        t = q.pop(0)
        if l:
            if l[0] != 'null':
                t.left = TreeNode(val=l.pop(0))
                q.append(t.left)
            else:
                l.pop(0)
        if l:
            if l[0] != 'null':
                t.right = TreeNode(val=l.pop(0))
                q.append(t.right)
            else:
                l.pop(0)
    return root


class Solution():
    def pathSum(self, root:Optional[TreeNode] , targetSum: int) -> List[List[int]]:
        # 迭代
        res = []

        if not root: return res
        from collections import deque
        que = deque()

        path = [root.val]
        que.append(root)  # 当前节点
        que.append(root.val)  # 当前路径和
        que.append(path)  # 当前路径

        while que:
            cur = que.popleft()
            sum_ = que.popleft()
            path = que.popleft()
            if not cur.left and not cur.right:  # 叶子节点
                if sum_ == targetSum:
                    res.append(path)
                else:
                    continue
            if cur.left:
                que.append(cur.left)
                que.append(sum_ + cur.left.val)
                que.append(path + [cur.left.val])
            if cur.right:
                que.append(cur.right)
                que.append(sum_ + cur.right.val)
                que.append(path + [cur.right.val])

        return res
    
if __name__ == "__main__":
    a = Solution()
    """ 二叉树debug """
    root = List2Tree([5,4,8,11,'null',13,4,7,2,'null','null',5,1]) # 把测试用例中的 null 换成 'null'
    targetSum = 22
    res = a.pathSum(root, targetSum)
    print(res) 
    # 输出[[5, 4, 11, 2], [5, 8, 4, 5]]

参考

https://blog.csdn.net/zhangsangood/article/details/108423558
https://blog.csdn.net/Mr_111000/article/details/119680459

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐