LeetCode(力扣)104. 二叉树的最大深度Python

LeetCode104. 二叉树的最大深度

    • 题目链接
    • 代码

题目链接

https://leetcode.cn/problems/maximum-depth-of-binary-tree/

LeetCode(力扣)104. 二叉树的最大深度Python_第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: Optional[TreeNode]) -> int:
        if not root:
            return 0
        queue = collections.deque([root])
        result = 0
        while queue:
            result += 1
            for _ in range(len(queue)):
                node = queue.popleft()
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)

        return result

递归

# 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: Optional[TreeNode]) -> int:
        
        return self.getmax(root)

    def getmax(self, node):
        if not node:
            return 0
        leftnode = self.getmax(node.left)
        rightnode = self.getmax(node.right)
        num = max(leftnode, rightnode) + 1
        return num

你可能感兴趣的:(leetcode,python,算法,linux)