剑指Offer55-I-二叉树的深度

剑指Offer55-I-二叉树的深度

输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。

例如:

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


    3

   / \

  9  20

    /  \

   15   7

返回它的最大深度 3 。

提示:

  • 节点总数 <= 10000

来源:力扣(LeetCode)

链接:力扣

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

一解

使用后序遍历,此树的深度等于左子树的深度与右子树的深度中的最大值 + 1 :max(root.left, root.right) + 1


# 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

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

  • 时间复杂度 O(N): N 为树的节点数量,计算树的深度需要遍历所有节点。

  • 空间复杂度 O(N): 最差情况下(当树退化为链表时),递归深度可达到 N 。