给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/
9 20
/
15 7
返回它的最大深度 3 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree
解法:递归
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
return self.digui(root,deepth=0)
def digui(self,root,deepth):
if root is None:
return deepth
else:
left = self.digui(root.left,deepth+1)
right = self.digui(root.right,deepth+1)
return max(left,right)
解法:层次遍历
维护一个队列存当前层的所有结点,先进先出更新队列
class Solution(object):
def maxDepth(self, root):
if not root:
return 0
queue = [root]
height = 0
while queue:
currentSize = len(queue)
for i in range(currentSize):
node = queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
height += 1
return height