代码随想录day16

遍历顺序:

后续遍历

核心逻辑:

使用max函数,取左右子树最大值递归‘

特殊点:

有返回值

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

题目二

遍历顺序:

后续遍历

核心逻辑:

使用min函数,取左右子树最小值递归‘

特殊点:

对于左子树为空、右子树存在

对于右子树为空、左子树存在的特殊情况进行处理,

class Solution(object):
    def minDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root is None:
            return 0
        
        left_h=self.minDepth(root.left)
        right_h=self.minDepth(root.right)

        if root.left is None and root.right is not None:
            return 1+ right_h
        
        if root.right is None and root.left is not None:
            return 1+left_h
        
        return min(left_h,right_h)+1

第三题

遍历顺序:

后续遍历

核心逻辑:

对每个结点来说,判断其是不是构成一个满二叉树

判断满二叉树:一直向左遍历的层数====一直向右遍历的层数

特殊点:

设立4个遍历

left,leftdepth,

right,rightdepth

判断每个节点是不是满二叉树

class Solution(object):
    def countNodes(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root is None:
            return 0
        
        left_h=1
        right_h=1
        left=root.left
        right=root.right

        while left:
            left_h+=1
            left=left.left
        
        while right:
            right_h+=1
            right=right.right

        if left_h==right_h:
            return  (2 ** left_h)-1
        
        ln=self.countNodes(root.left) #左
        rn=self.countNodes(root.right) #右
        return ln+rn+1 #中

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值