代码随想录算法训练营第十六天 | 二叉树 part 3 | 树的深度、222.完全二叉树的节点个数

文章介绍了如何计算二叉树的最大深度(递归、迭代和层序遍历)、二叉树的最小深度(特殊处理非空子节点情况)、以及n叉树的最大深度和完全二叉树的节点个数两种方法,包括递归和非递归实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

104.二叉树的最大深度

Leetcode
在这里插入图片描述
树的最大深度就是根节点的高度。求高度用后序遍历,求深度用前序遍历。也可以用层序遍历,每遍历一层,depth += 1.

下图是卡哥视频里的截图
在这里插入图片描述

class solution:
    def maxdepth(self, root: treenode) -> int:
        return self.getdepth(root)
        
    def getdepth(self, node):
        if not node:
            return 0
        leftheight = self.getdepth(node.left) #左
        rightheight = self.getdepth(node.right) #右
        height = 1 + max(leftheight, rightheight) #中
        return height

559. n叉树的最大深度

Leetcode

在这里插入图片描述

代码

递归

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        return self.getDepth(root)

    def getDepth(self, root):
        if not root:
            return 0
        
        left = self.getDepth(root.left)
        right = self.getDepth(root.right)
        return 1 + max(left, right)

迭代

层序遍历 bfs
"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

class Solution:
    def maxDepth(self, root: 'Node') -> int:
        if not root:
            return 0
        
        q = deque([root])
        depth = 0

        while q:
            depth += 1
            for _ in range(len(q)):
                node = q.popleft()
                for child in node.children:
                    q.append(child)
                
        return depth
dfs-------栈
"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

class Solution:
    def maxDepth(self, root: 'Node') -> int:
        if not root:
            return 0
        
        stack = [(root, 1)]
        max_depth = 0
        while stack:
            node, depth = stack.pop()
            max_depth = max(max_depth, depth)
            for child in node.children:
                stack.append((child, depth + 1))
        
        return max_depth

111.二叉树的最小深度

Leetcode

在这里插入图片描述

思路

求最小深度和最大深度的思路有些不一样。因为最小深度的定义如下:最小深度是从根节点到最近叶子节点(左右孩子都为空的节点才是叶子节点)的最短路径上的节点数量
在这里插入图片描述
如果只是在递归的时候return 1 + min(left, right)那么对于上图就会返回最小深度为1。所以,我们需要针对这种情况写多一些case。

求二叉树的最小深度和求二叉树的最大深度的差别主要在于处理左右孩子不为空的逻辑。

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0

        left = self.minDepth(root.left)
        right = self.minDepth(root.right)
        if root.left and not root.right:
            return 1 + left
        elif not root.left and root.right:
            return 1 + right
        elif not root.left and not root.right:
            return 1
        else:
            return 1 + min(left, right)

222.完全二叉树的节点个数

Leetcode在这里插入图片描述

思路

第一种使用后序遍历的方式来记录node个数

第二种利用完全二叉树的性质。

在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h h h 层,则该层包含的节点在 [ 1 , 2 ( h − 1 ) ] [1, 2^{(h-1)}] [1,2(h1)] 区间。

在这里插入图片描述
对于完全二叉树,只要左右同时向下遍历,如果长度相等则为满二叉树,那么则可以用 2 h − 1 2^h - 1 2h1来计算其中node个数。

代码

后序遍历递归

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0

        left = self.countNodes(root.left)
        right = self.countNodes(root.right)
        return 1 + left + right
  • 时间复杂度:O(n)
  • 空间复杂度:O(log n),算上了递归系统栈占用的空间(在python里面也是这样吗?

完全二叉树递归

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0

        count = 1

        left, right = root.left, root.right
        while left and right:
            count += 1
            left = left.left
            right = right.right
        
        if not left and not right:
            return 2**count - 1

        return 1 + self.countNodes(root.left) + self.countNodes(root.right)
  • 时间复杂度:O(log n × log n)
  • 空间复杂度:O(log n)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值