leetcode_104 二叉树的最大深度

70 阅读1分钟

要求

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例: 给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

核心代码

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:
        def max_depth(root):
            if not root:
                return 0
            max_left = max_depth(root.left)
            max_right = max_depth(root.right)
            return max(max_left,max_right) + 1
        return max_depth(root)

另一解法

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:
        stack = []
        if root:
            stack.append((root,1))
        max_depth = 0
        while stack:
            tree_node,cur_depth = stack.pop()
            if tree_node:
                max_depth = max(max_depth,cur_depth)
                stack.append((tree_node.left,cur_depth+1))
                stack.append((tree_node.right,cur_depth+1))
        return max_depth

image.png

解题思路:第一种解法:我们使用递归的方法,回归到最大的深度;第二种解法:我们使用迭代法,我们对树进行层次遍历,不断的向列表中加入节点和深度,最后遍历完整个列表就能得到最大的深度。