您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页LeetCode 104. 二叉树的最大深度

LeetCode 104. 二叉树的最大深度

来源:二三娱乐

题目

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回它的最大深度 3 。

解题思路

递归

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        return self.countTree(root, 1, 0)

    def countTree(self, tree: TreeNode, rank: int, maxRank: int) -> int:
        if tree is None: return 0
        leftRank = 0
        rightRank = 0
        if tree is not None:
            maxRank = max(rank, maxRank)
        if tree.left is not None:
            leftRank = self.countTree(tree.left, rank+1, maxRank)
        if tree.right is not None:
            rightRank = self.countTree(tree.right, rank+1, maxRank)
        maxRank = max(maxRank, leftRank, rightRank)
        return maxRank

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务