代码随想录算法训练营17期day15-python(递归)

一、二叉树的最大深度

1、递归

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        # 判断节点是否为0,返回0,同时是递归的边界
        if not root:
            return 0
        # 左子树的深度,向左递归,后序遍历第一步
        leftDepth = self.maxDepth(root.left)
        # 右子树的深度,向右递归,后续遍历第二步
        rightDepth = self.maxDepth(root.right)
        # 根节点的最大深度,等于左右子树深度的中的较大值加1
        depth = 1 + max(leftDepth, rightDepth)
        return depth

 二、二叉树的最小深度

1、递归

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def minDepth(self, root):
        if root is None:
            return 0
        if root.left is None and root.right is not None:
            return 1 + self.minDepth(root.right)
        if root.left is not None and root.right is None:
            return 1 + self.minDepth(root.left)
        #此处注意一点,当左右子树均为空时,也可以执行下面语句,因为左右子树的深度相等
        return 1 + min(self.minDepth(root.left), self.minDepth(root.right))

三、完全二叉树的节点数

递归 + 完全二叉树的特性

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def countNodes(self, root: TreeNode) -> int:
        return self.getNodesNum(root)

    def getNodesNum(self, cur):
        # 采用后续遍历顺序
        if not cur:
            return 0
        # 此方法适用于所有种类的二叉树,属于普遍方法
        leftNum = self.getNodesNum(cur.left)  # 左
        rightNum = self.getNodesNum(cur.right)  # 右
        treeNum = leftNum + rightNum + 1  # 中
        return treeNum
    
    
class Solution1:
    def countNodes(self, root: TreeNode) -> int:
        if not root:
            return 0
        left = root.left
        right = root.right
        leftDepth = 0 #这里初始为0是有目的的,为了下面求指数方便
        rightDepth = 0
        while left: #求左子树深度
            left = left.left
            leftDepth += 1
        while right: #求右子树深度
            right = right.right
            rightDepth += 1
        if leftDepth == rightDepth:
            return (2 << leftDepth) - 1 #注意(2<<1) 相当于2^2,所以leftDepth初始为0
        return self.countNodes(root.left) + self.countNodes(root.right) + 1

你可能感兴趣的:(python,算法,开发语言,leetcode)