刷题第十四天 104.二叉树的最大深度 111. 二叉树最小深度 222.完全二叉树节点个数

104. 二叉树最大深度

广度优先遍历(层序遍历):

#### 层序遍历 ####
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        result = 0
        if not root:
            return result
        from collections import deque
        _list = deque()
        _list.append(root)
        while(_list):
            for _ in range(len(_list)):
                node = _list.popleft()
                if node.left:
                    _list.append(node.left)
                if node.right:
                    _list.append(node.right)
            result += 1
        return result

后序遍历

class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        def get_height(node):
            if not node:
                return 0
            left_height = get_height(node.left)          #左
            right_height = get_height(node.right)        #右
            height = 1 + max(left_height, right_height)  #中
            return height
        return get_height(root)

111. 最小深度

class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        def get_height(node):
            if not node:
                return 0
            left_height = get_height(node.left)
            right_height = get_height(node.right)
            if not node.left and node.right:
                height = 1 + right_height
            elif node.left and not node.right:
                height = 1 + left_height
            else:
                height = 1 + min(left_height, right_height)
            return height
        return get_height(root)

和最大深度差别在于处理的方式,碰到空的情况不能算深度

222. 完全二叉树节点个数

class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        leftNum = self.countNodes(root.left)
        rightNum = self.countNodes(root.right)
        Num = leftNum + rightNum + 1
        return Num

递归还是得想想

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值