104.Maximum_Depth_of_Binary_Tree

25 年 7 月 1 日 星期二
262 字
2 分钟

104. Maximum Depth of Binary Tree

解法一 自顶向下

py
# 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:
        ans = 0
        if not root: return 0
        def dfs(root, d):
            nonlocal ans
            if not root:
                ans = max(ans, d)
                return
            d += 1
            dfs(root.left, d)
            dfs(root.right, d)
        dfs(root, 0)
        return ans

Notice that there is nonlocal ans inside dfs function. If not UnboundLocalError will be raise.

Why ans.append will not cause this, because it is no re-assignment.

时空复杂度都是O(n)

Time: 每个节点都遍历一次

Space: 最坏情况下是O(n) 树类似链表

解法二 自底向上

python
class Solution:
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        if root is None:
            return 0
        l_depth = self.maxDepth(root.left)
        r_depth = self.maxDepth(root.right)
        return max(l_depth, r_depth) + 1

作者:灵茶山艾府
链接:https://leetcode.cn/problems/maximum-depth-of-binary-tree/solutions/2010612/kan-wan-zhe-ge-shi-pin-rang-ni-dui-di-gu-44uz/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

return max(l_depth, r_depth) + 1 这里的 +1 是把当前节点计算进去

当前树高等于左右子树最大高度加一

解法二更类似于DP的思想

文章标题:104.Maximum_Depth_of_Binary_Tree

文章作者:Sirui Chen

文章链接:https://blog.siruichen.me/posts/104maximum_depth_of_binary_tree[复制]

最后修改时间:


商业转载请联系站长获得授权,非商业转载请注明本文出处及文章链接,您可以自由地在任何媒体以任何形式复制和分发作品,也可以修改和创作,但是分发衍生作品时必须采用相同的许可协议。
本文采用CC BY-NC-SA 4.0进行许可。