剑指 Offer 55

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

例如:

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

3
/ 
9 20
/ 
15 7
返回它的最大深度 3 。

 

提示:

节点总数 <= 10000
  • 解法一:后序遍历(DFS)

利用二叉树的后序遍历思想,分别遍历二叉树左右子树的最大深度,则此树的深度为左右子树深度的最大值+1。

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if not root: #越过叶节点,返回深度为0
            return 0
        return max(self.maxDepth(root.left), self.maxDepth(root.right))+1 

间复杂度O(N),空间复杂度O(N)

  • 解法二:层序遍历(BFS)

    def maxDepth(self, root: TreeNode) -> int:
        queue = []
        res = 0
        if not root:
            return 0
        queue.append(root)
        while queue:
            tmp = []
            for node in queue:
                if node.left:
                    tmp.append(node.left)
                if node.right:
                    tmp.append(node.right)
            queue = tmp #每一层的左右子树都保存在tmp里面
            res += 1 #res用来记录层数
        return res

间复杂度O(N),空间复杂度O(N)

参考链接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/solution/mian-shi-ti-55-i-er-cha-shu-de-shen-du-xian-xu-bia/

原文地址:https://www.cnblogs.com/yeshengCqupt/p/13462456.html