二叉树的最大深度Python3

问题提出:
给定一个二叉树,找出其最大深度。二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。

解决思路:递归法求解。从根结点向下遍历,每遍历到子节点depth+1。

代码实现( ̄▽ ̄):

# 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 root==None:
            return 0
        count = self.getDepth(root,0)
        return count
    
    def getDepth(self,node,count):
        if node!=None:
            num1 = self.getDepth(node.left,count+1);
            num2 = self.getDepth(node.right,count+1);
            num = num1 if num1>num2 else num2
            return num
        else:
            return count

时间和空间消耗:

问题来源:https://leetcode-cn.com/probl…

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理