美文网首页
104. Maximum Depth of Binary Tre

104. Maximum Depth of Binary Tre

作者: 羲牧 | 来源:发表于2020-07-16 08:47 被阅读0次

首先是递归的解法

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if root is None:
            return 0
        return max(self.maxDepth(root.left)+1, self.maxDepth(root.right)+1)
        

然后是队列的解法:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if root is None:
            return 0
        queue = [root]
        result = 0
        while len(queue):
            result += 1
            length = len(queue)
            while length:
                # 注意:这里需要删除队头元素
                p = queue.pop(0)
                length = length - 1
                if p.left:
                    queue.append(p.left)
                if p.right:
                    queue.append(p.right)
                
        return result
            
        
        

相关文章

网友评论

      本文标题:104. Maximum Depth of Binary Tre

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