一、题目
题目链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
题目描述:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树[3,9,20,null,null,15,7]
,3 / \ 9 20 / \ 15 7返回它的最大深度 3 。
二、分析及代码
1.递归方法:
递归是最容易想到的一种方法,判断如果传入的节点为空,则返回0,否则返回左节点和右节点的最大值+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 root==None: return 0 return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
2.层次遍历方法:
可以采用层次遍历,每遍历一层,深度值+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 root==None: return 0 presub = [root] p = root sub = [] d = 1 while p!=None or len(presub)!=0: while len(presub)!=0: p = presub.pop(0) if p.left!=None: sub.append(p.left) if p.right!=None: sub.append(p.right) presub = sub if len(sub)!=0: d+=1 else: return d sub = [] return d