给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
点击查看DFS的代码
class Solution:
def maxDepth(self, root) -> int:
if not root:
return 0
# 利用定义,计算左右子树的最大深度
left = self.maxDepth(root.left)
right = self.maxDepth(root.right)
# 整棵树的最大深度等于左右子树的最大深度取最大值,然后再加上根节点自己
return max(left, right) + 1
点击查看BFS的代码
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root is None:
return 0
q = deque([root])
level = 0
while q:
n = len(q)
for i in range(n):
node = q.popleft()
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
level += 1
return level
点击查看pycharm-DFS代码
from collections import deque
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root is None:
return 0
q = deque([root])
level = 0
while q:
n = len(q)
for i in range(n):
node = q.popleft()
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
level += 1
return level
if __name__ == '__main__':
# 创建根节点
root = TreeNode(3)
# 插入左右子节点
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
# 创建一个 Solution 对象
solution = Solution()
# 计算整棵树的
# 计算整棵树的最大深度
depth = solution.maxDepth(root)
print(depth)
点击查看pycharm-BFS代码
from collections import deque
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root is None:
return 0
q = deque([root])
level = 0
while q:
n = len(q)
for i in range(n):
node = q.popleft()
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
level += 1
return level
if __name__ == '__main__':
# 创建根节点
root = TreeNode(3)
# 插入左右子节点
root.left = TreeNode(9)
root.right = TreeNode(20)
root.right.left = TreeNode(15)
# 创建一个 Solution 对象
solution = Solution()
# 计算整棵树的
# 计算整棵树的最大深度
depth = solution.maxDepth(root)
print(depth)
总结
Python中collections模块(高性能集合操作)
deque([list]).popleft():弹出list最左侧的元素;