算法刷题-数据结构篇

本文详细探讨了二叉树的深度、二叉搜索树的第k大节点、不同类型的遍历以及构建方法。此外,还涉及了单链表的删除、倒数第k个节点查找、插入、逆序和重复元素删除。最后,讨论了有向图的拓扑排序问题,结合LeetCode的经典题目进行解析。
摘要由CSDN通过智能技术生成

1.树

1.1 二叉树

1.1.1 二叉树的深度
 # Definition for a binary tree node.
 class TreeNode:
     def __init__(self, x):
         self.val = x
         self.left = None
         self.right = None

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        ldepth = Solution.maxDepth(self, root.left)
        rdepth = Solution.maxDepth(self, root.right)
        return max(ldepth, rdepth) + 1
1.1.2 二叉搜索树的第k大节点
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def kthLargest(self, root: TreeNode, k: int) -> int:
        def func(root):
            return func(root.left) +[root.val]+func(root.right) if root else []

        return func(root)[-k]

1.1.3 二叉树的遍历
先序遍历
#递归
def pre_order(root):
    if not root:
        return []
    return [root.val]+pre_order(root.left)+pre_order(root.right)
#非递归
def pre_order(root):
    if not root:
        return 
    stack=[]
    stack.append(root)
    ret=[]
    while stack:
        x=stack.pop()
        ret.append(x.val)
        if x.right:
            stack.append(x.right)
        if x.left:
            stack.append(x.left)
中序遍历
#递归
def mid_order(root):
    if not root:
        return []
    return mid_order(root.left)+[root.val]+mid_order(root.right)
#非递归
def mid_order(root):
    if not root:
        return 
    stack=[]
    stack.append(root)
    ret=[]
    while stack:
        x=stack.pop()
        if x.right:
            stack.append(x.right)
        ret.append(x.val)
        if x.left:
            stack.append(x.left)
后序遍历
# 递归
def post_order(root):
    if not root:
        return []
    return post_order(root.left)+post_order(root.right)+[root.val]
# 非递归
def post_order(root):
    if not root:
        return 
    stack=[]
    stack.append(root)
    ret=[]
    while stack:
        x=stack.pop()
        if x.right:
            stack.append(x.right)
        if x.left:
            stack.append(x.left)
        ret.append(x
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值