day16|二叉树3

104.二叉树的最大深度

在这里插入图片描述

前序(中左右),也可以使用后序遍历(左右中),使用前序求的就是深度,使用后序求的是高度。

  • 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
  • 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数后者节点数(取决于高度从0开始还是从1开始)

根节点的高度就是二叉树的最大深度。真正求解深度应该使用高度,即后序遍历。
中序遍历和后序遍历的不同之处在于根节点的访问位置不同,看递归的返回值返回给哪一个值。

递归法

按照中左右的顺序找到树的最大深度,注意递归函数体的写法。

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        def depthfunc(node):
            if not node:
                return 0 
            leftdepth = depthfunc(node.left) + 1
            rightdepth = depthfunc(node.right) + 1
            depth = max(leftdepth,rightdepth)
            return depth
        return depthfunc(root)

111.二叉树的最小深度

在这里插入图片描述
最小深度: 根节点到叶子结点的最小距离为最小深度。
前序遍历是求深度的过程,但是本题使用后序代码更简便。

class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        def getDepth(node):
            if not node:
                return 0
            leftdepth = getDepth(node.left)  # 左
            rightdepth = getDepth(node.right)  # 右
            # 在求最小深度的过程中,需要注意为0的情况,和求最大深度不同点在于需要对左右子树的高度是否为0进行判断
            if not node.left and node.right:
                depth = 1 + rightdepth # 中
            elif not node.right and node.left:
                depth = 1 + leftdepth # 中
            elif node.left and node.right:
                depth = 1 + min(leftdepth,rightdepth) # 中
            else:
                depth = 1 # 中
            return depth
        return getDepth(root)

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

利用左右中的顺序进行遍历,将左右孩子的节点数返回给父节点。
在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2^(h-1) 个节点。
满二叉树:在完全二叉树的基础上判断最左和最右的结点数量是否相等即可。

class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        def getNum(node):
            if not node:
                return 0 
            leftNum = getNum(node.left) 
            rightNum = getNum(node.right) 
            num = leftNum + rightNum + 1
            return num
        return getNum(root) 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值