LeetCode 104. 二叉树的最大深度

作者: freesan44 | 来源:发表于2020-02-25 08:38 被阅读0次

题目

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

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

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

示例:
给定二叉树 [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

相关文章

网友评论

    本文标题:LeetCode 104. 二叉树的最大深度

    本文链接:https://www.haomeiwen.com/subject/hwbwqhtx.html