【python实现】 104. 二叉树的最大深度

给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
在这里插入图片描述
思路:
递归,比较每一条路径的长短
解答:

# 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:
        if not root:
            return 0
        left = self.maxDepth(root.left)+1
        right = self.maxDepth(root.right)+1
        
        return max(left, right)

转载自
https://blog.csdn.net/qiubingcsdn/article/details/82381788

猜你喜欢

转载自blog.csdn.net/qq_41929011/article/details/87928370