代码随想录算法训练营第16天|104.二叉树的最大深度 111.二叉树的最小深度 222.完全二叉树的节点个数

104.二叉树的最大深度 (优先掌握递归)

题目链接:LeetCode - The World's Leading Online Programming Learning Platform

题目链接/文章讲解/视频讲解: 代码随想录

解题思路:

递归思路左右中 先递归左的 在递归右的高度 当前中的高度为1+leftheight和rightheight中大的数。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0
        left=self.maxDepth(root.left)
        right=self.maxDepth(root.right)
        height=1+max(left,right)
        return height

111.二叉树的最小深度 (优先掌握递归)

题目链接:LeetCode - The World's Leading Online Programming Learning Platform

题目链接/文章讲解/视频讲解:代码随想录

解题思路:

和最大深度差不多 

递归思路左右中 先递归左的 再递归右的高度

如果左子树为空右子树不为空的话 注意不能return当前中的高度为1+leftheight和rightheight中小的数 要return 1+右子树的高度 因为题目要求root到leaf的距离。 

同理 当右子树为空左子树不为空的话 return 1+左子树的高度。

如果左右都不为空 就return1+leftheight和rightheight中小的数

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root is None:
            return 0
        if root.left is None and root.right is None:
            return 1
        leftheight = self.minDepth(root.left)
        rightheight = self.minDepth(root.right)
        if root.left == None and root.right !=None:
            return 1 + rightheight
        if root.right == None and root.left != None:
            return 1 + leftheight
        return 1 + min(leftheight,rightheight)

222.完全二叉树的节点个数(优先掌握递归)

题目链接:LeetCode - The World's Leading Online Programming Learning Platform

题目链接/文章讲解/视频讲解:代码随想录

解题思路:

左右中 递归数左子树 递归数右子树 最后结合左右子树再加1(中)

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def countNodes(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root is None:
            return 0
        leftcount=self.countNodes(root.left)
        rightcount=self.countNodes(root.right)
        return 1+leftcount+rightcount

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值