二叉树的最大深度(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

时间和空间消耗:

clipboard.png

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章