【剑指offer】面试题55

题目描述

面试题55 - I. 二叉树的深度

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

例如:

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

    3
   /
  9  20
    / 
   15   7

返回它的最大深度 3 。

分析

1.广度优先遍历 BFS

和上几道题层次遍历一个思路,采用先入先出的队列数据结构,初始化一个dep变量,每加一层加一

2.深度优先搜索(DFS)

用到递归,深度为根节点左右子树的深度max+1

解题

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
        temp=[root]
        dep=0
        while(temp):
            dep+=1
            length = len(temp)
            for i in range(length):
                cur=temp.pop(0)
                if(cur.left):
                    temp.append(cur.left)
                if(cur.right):
                    temp.append(cur.right)  
        return dep

2.

# 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(self.maxDepth(root.left), self.maxDepth(root.right))+1
原文地址:https://www.cnblogs.com/fuj905/p/12910088.html