Leetcode 104:二叉树的最大深度(最详细的解法!!!)

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

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

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

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

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

解题思路

整个问题一个很简单的思路就是使用递归。怎么做呢?我们只要通过maxDepth分别计算出左子树和右子树的深度,比较这两个深度,取最大值k。那么当前这棵树深度的最大值就变成了k + 1。So easy!!O(∩_∩)O

class Solution:
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return 0

        return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

当然我们可以写得更加简洁

class Solution:
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        return 0 if not root else max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1

但是还没有结束,对于可以用递归解决的问题,我们都应该思考一下怎么可以通过迭代去解决。那这个问题怎么通过迭代解决呢?那么我们就会用到stack,通过stack模拟上面的递归过程。一个较为简单的思路就是二叉树的层序遍历,参看这篇Leetcode 102:二叉树的层次遍历(最详细解决方案!!!) ,我们在此基础上稍加修改就可以了。

class Solution:
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        q = [(root, 1)]
        result = 0
        while q:
            node, depth = q.pop(0)
            if node:
                result = max(result, depth)
                q.extend([(node.left, depth + 1), (node.right, depth + 1)])

        return result

我将该问题的其他语言版本添加到了我的GitHub Leetcode

如有问题,希望大家指出!!!

猜你喜欢

转载自blog.csdn.net/qq_17550379/article/details/81586617