hot100-二叉树I

94. 二叉树的中序遍历

94. 二叉树的中序遍历 - 力扣(LeetCode)

python 复制代码
class Solution(object):
    def inorderTraversal(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: List[int]
        """
        def inorder(root):
            if not root:
                return
            inorder(root.left)
            res.append(root.val)
            inorder(root.right)
        res = []
        inorder(root)
        return res

补充:前序遍历 and 后序遍历

python 复制代码
class Solution(object):
    def inorderTraversal(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: List[int]
        """
        def inorder(root):
            if not root:
                return
            inorder(root.left)
            res.append(root.val)
            inorder(root.right)
        res = []
        inorder(root)
        return res

    def preorderTraversal(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: List[int]
        """
        def preorder(root):
            if not root:
                return
            res.append(root.val)
            preorder(root.left)
            preorder(root.right)
        res = []
        preorder(root)
        return res

    def postorderTraversal(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: List[int]
        """
        def postorder(root):
            if not root:
                return
            postorder(root.left)
            postorder(root.right)
            res.append(root.val)
        res = []
        postorder(root)
        return res

遍历迭代版本

python 复制代码
class Solution(object):
    def inorderTraversal(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: List[int]
        """
        st = []
        res = []
        p = root
        while p or st:
            # 先找到最左边的节点
            while p:
                st.append(p)
                p = p.left
            # st的最后一个元素就是最左边的节点
            p = st.pop()
            res.append(p.val)
            # 处理右子树
            p = p.right
        return res
        
    def preorderTraversal(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: List[int]
        """
        if not root:
            return []
        st = [root]
        res = []
        while st:
            p = st.pop()
            res.append(p.val)
            # 先压入右节点,让左节点先弹出
            if p.right:
                st.append(p.right)
            if p.left:
                st.append(p.left)
        return res
        
    def postorderTraversal(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: List[int]
        """
        if not root:
            return []
        st = [root]
        res = []
        while st:
            p = st.pop()
            res.append(p.val)
            # 先压入左节点,让右节点先弹出
            if p.left:
                st.append(p.left)
            if p.right:
                st.append(p.right)
        # 头 右 左
        # 翻转:左 右 头
        return res[::-1]

空间复杂度:O(n)

时间复杂度:O(n)

104. 二叉树的最大深度

104. 二叉树的最大深度 - 力扣(LeetCode)

深搜版本:

python 复制代码
class Solution(object):
    def maxDepth(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: int
        """
        # 深搜
        if not root:
            return 0
        left_h = self.maxDepth(root.left)
        right_h = self.maxDepth(root.right)
        return max(left_h,right_h)+1
python 复制代码
class Solution(object):
    def maxDepth(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: int
        """
        # 深搜
        return 0 if not root else max(self.maxDepth(root.left),self.maxDepth(root.right))+1

时间复杂度:O(N)

空间复杂度:O(H) 【H 平均是log N的高度,最差是N】

python 复制代码
class Solution(object):
    def maxDepth(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: int
        """
        # 广搜
        if not root:
            return 0
        queue = [(root,1)]
        while queue:
            node,height = queue.pop(0)
            if node.left: queue.append((node.left,height+1))
            if node.right:queue.append((node.right,height+1))
        return height

时间复杂度:O(N)

空间复杂度:O(N)

226. 翻转二叉树

226. 翻转二叉树 - 力扣(LeetCode)

python 复制代码
class Solution(object):
    def invertTree(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: Optional[TreeNode]
        """
        if not root:
            return root
        root.left,root.right = self.invertTree(root.right),self.invertTree(root.left)
        return root

时间复杂度:O(N)

空间复杂度:O(H) 【H 平均是log N的高度,最差是N】

101. 对称二叉树

101. 对称二叉树 - 力扣(LeetCode)

递归:

python 复制代码
class Solution(object):
    def check(self,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 self.check(left.left,right.right) and self.check(left.right,right.left)

    def isSymmetric(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: bool
        """
        if not root:
            return True
        return self.check(root.left,root.right)

时间复杂度:O(N)

空间复杂度:O(N)

迭代:

python 复制代码
class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: bool
        """
        if not root:
            return True
        queue = [root.left,root.right]
        while queue:
            left = queue.pop(0)
            right = queue.pop(0)
            if not left and not right:
                continue
            if (not left or not right) or left.val != right.val:
                return False
            queue.append(left.left)
            queue.append(right.right)
            queue.append(left.right)
            queue.append(right.left)
        return True

时间复杂度:O(N)

空间复杂度:O(N)

543. 二叉树的直径

543. 二叉树的直径 - 力扣(LeetCode)

python 复制代码
class Solution(object):
    def depth(self,root):
        if not root:
            return 0
        left_h = self.depth(root.left)
        right_h = self.depth(root.right)
        self.ans = max(self.ans,left_h+right_h)
        return max(left_h,right_h)+1

    def diameterOfBinaryTree(self, root):
        """
        :type root: Optional[TreeNode]
        :rtype: int
        """
        # 任意一颗子树的直径都可以表示为(左子树深度+右子树深度+1)-1 = 左子树深度+右子树深度
        # 我们只要利用ans记录最大值即可【这个直径不一定出现在根节点,想象一颗左子树和右子树极度不平衡的树】
        #     1
        #    2 
        #   3  4
        #  5     6
        self.ans = 0
        self.depth(root)
        return self.ans

时间复杂度:O(N)

空间复杂度:O(H) 【H 平均是log N的高度,最差是N】

相关推荐
AC赳赳老秦19 小时前
OpenClaw+Power Apps 实战:自动生成 Power Apps 应用、连接 Excel 数据源
大数据·开发语言·python·serverless·excel·deepseek·openclaw
一只齐刘海的猫19 小时前
【Leetcode】找到字符串中所有字母异位词
算法·leetcode·职场和发展
海清河晏11119 小时前
数据结构 | 八大排序
数据结构·算法·排序算法
liulilittle20 小时前
固定数组时间轮的槽过载优化:桶链表与批次执行
网络·数据结构·链表
IronMurphy21 小时前
【算法五十七】146. LRU 缓存
算法·缓存
茉莉玫瑰花茶21 小时前
综合案例 - AI 智能租房助手 [ 5 ]
服务器·数据库·人工智能·python·ai
文艺倾年21 小时前
【强化学习】强化学习基本概念,20W字总结(一)
人工智能·python·语言模型·自然语言处理·面试·职场和发展·大模型
宸丶一21 小时前
Day 13:持久化记忆 - 让 Agent 拥有长期记忆
jvm·python·ai
Irissgwe21 小时前
数据结构-栈和队列
数据结构·c++·c·栈和队列
两片空白21 小时前
数据容器集合set/frozenset
数据结构