天天看點

LeetCode104.二叉樹的最大深度 (BFS)+(遞歸)兩種方法LeetCode104.二叉樹的最大深度 (BFS)+(遞歸)兩種方法

LeetCode104.二叉樹的最大深度 (BFS)+(遞歸)兩種方法

BFS

# 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
        q = []
        q.append(root)
        ans = 0
        while q:
            tmp = []
            for i in q:
                if i.left:
                    tmp.append(i.left)
                if i.right:
                    tmp.append(i.right)
            ans += 1
            q = tmp
        return ans
           

遞歸

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