讨论/《二叉树》 - 二叉树的最大深度/
《二叉树》 - 二叉树的最大深度

python 实现

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        # 自顶向下
        Solution.answer = 0
        def depth(root, d):
            if not root: return 
            if not root.left and not root.right:
                Solution.answer = max(Solution.answer, d)
            depth(root.left, d+1)
            depth(root.right, d+1)
        
        depth(root, 1)
        return Solution.answer

        # 自底向上
        # def maxDep(root):
        #     if not root: return 0
        #     return max(maxDep(root.left), maxDep(root.right)) + 1
        # index = maxDep(root)
        # return index


        # 层次遍历改版
        # index = 0
        # if not root: return 0
        # queue = [root]
        # while queue:
        #     index += 1
        #     for i in range(len(queue)):
        #         cur_node = queue.pop(0)
        #         if cur_node.left:
        #             queue.append(cur_node.left)
        #         if cur_node.right:
        #             queue.append(cur_node.right)
        # return index
展开全部 13 讨论