LeetCode Hot100 刷题笔记(4)—— 二叉树、图论

目录

一、二叉树

1. 二叉树的深度遍历(DFS:前序、中序、后序遍历)

2. 二叉树的最大深度

3. 翻转二叉树

4. 对称二叉树

5. 二叉树的直径

6. 二叉树的层序遍历

7. 将有序数组转换为二叉搜索树

8. 验证二叉搜索树

9. 二叉搜索树中第 K 小的元素

10. 二叉树的右视图

11. 二叉树展开为链表

12. 从前序与中序遍历序列构造二叉树

13. 路径总和 III

14. 二叉树的最近公共祖先

15. 二叉树中的最大路径和

二、图论

1. 岛屿数量

2. 腐烂的橘子

3. 课程表

4. 实现 Trie (前缀树)


前言

一、二叉树:二叉树的中序遍历,二叉树的最大深度,翻转二叉树,对称二叉树,二叉树的直径,二叉树的层序遍历,将有序数组转换为二叉搜索树,验证二叉搜索树,二叉搜索树中第 K 小的元素,二叉树的右视图,二叉树展开为链表,从前序与中序遍历序列构造二叉树,路径总和 III,二叉树的最近公共祖先,二叉树中的最大路径和。

二、图论:岛屿数量,腐烂的橘子,课程表,实现 Trie (前缀树)。


一、二叉树

1. 二叉树的深度遍历(DFS:前序、中序、后序遍历)

 原题链接:94. 二叉树的中序遍历 - 力扣(LeetCode)

# (1)前序遍历:根-左-右
class Solution(object):
    def preorderTraversal(self, root):
        res = []
        def preorder(root):
            if not root:
                return 
            res.append(root.val)
            preorder(root.left)
            preorder(root.right)
        preorder(root)
        return res
# (2)中序遍历:左-根-右
class Solution(object):
    def inorderTraversal(self, root):
        res = []
        def inorder(root):
            if not root:
                return 
            inorder(root.left)
            res.append(root.val)
            inorder(root.right)
        inorder(root)
        return res

# (3)后序遍历:左-右-根
class Solution(object):
    def postorderTraversal(self, root):
        res = []
        def inorder(root):
            if not root:
                return 
            postorder(root.left)
            postorder(root.right)
            res.append(root.val)
        postorder(root)
        return res

2. 二叉树的最大深度

原题链接:104. 二叉树的最大深度 - 力扣(LeetCode)

class Solution(object):
    def maxDepth(self, root):
        if not root:
            return 0
        left_height = self.maxDepth(root.left)
        right_height = self.maxDepth(root.right)
        return max(left_height, right_height) + 1

3. 翻转二叉树

原题链接:226. 翻转二叉树 - 力扣(LeetCode)

class Solution(object):
    def invertTree(self, root):
        if not root:
            return 
        root.left, root.right = root.right, root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root

4. 对称二叉树

原题链接:101. 对称二叉树 - 力扣(LeetCode)

class Solution(object):
    def isSymmetric(self, root):
        def check(left, right):
            if not left and not right:
                return True
            if not left or not right:
                return False
            if left.val != right.val:
                return False
            return check(left.left, right.right) and check(left.right, right.left)
        return check(root.left, root.right)

5. 二叉树的直径

原题链接:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值