代码随想录算法训练营第16天|二叉树(三)

题目链接:104. 二叉树的最大深度

思路:后续遍历递归法;遍历左子树高度,右子树高度,最后加上根节点所在层级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 getDepth(self,node):
        if not node:
            return 0
        left_depth=self.getDepth(node.left)
        right_depth=self.getDepth(node.right)
        return max(left_depth,right_depth)+1
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        return self.getDepth(root)
        


题目链接:111. 二叉树的最小深度

思路:后续遍历递归法,求左子树和右子树的最小值;注意和最大深度不同的情况是,若左子树为空,深度为右子树深度加1;若右子树为空,深度为左子树深度加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 getDepth(self,node):
        if not node:
            return 0
        leftDepth=self.getDepth(node.left)
        rightDepth=self.getDepth(node.right)
        if node.left is None and node.right is not None:
            return rightDepth+1
        if node.right is None and node.left is not None:
            return leftDepth+1
        return min(leftDepth,rightDepth)+1
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        return self.getDepth(root)

        


题目链接:222. 完全二叉树的节点个数

思路:后序遍历递归。左子树节点树+右子树节点树+根节点

# 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 getCount(self,node):
        if not node:
            return 0
        leftCount=self.getCount(node.left)
        rightCount=self.getCount(node.right)
        return leftCount+rightCount+1
    def countNodes(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        return self.getCount(root)
        

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值