您的位置:首页 > 房产 > 建筑 > 线上推广公司排名_logo免费设计在线生成app_seo运营_北京网络网站推广

线上推广公司排名_logo免费设计在线生成app_seo运营_北京网络网站推广

2025/7/20 12:09:12 来源:https://blog.csdn.net/weixin_45535091/article/details/146515377  浏览:    关键词:线上推广公司排名_logo免费设计在线生成app_seo运营_北京网络网站推广
线上推广公司排名_logo免费设计在线生成app_seo运营_北京网络网站推广

题目:

给定一个二叉树 root ,返回其最大深度。

二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。

示例 1:

输入:root = [3,9,20,null,null,15,7]
输出:3

示例 2:

输入:root = [1,null,2]
输出:2

提示:

  • 树中节点的数量在 [0, 104] 区间内。
  • -100 <= Node.val <= 100

解题思路:

使用深度优先搜索的思想,用栈存储当前的节点地址和节点的深度,如果遍历到树叶节点就将栈顶元素输出,height返回到上一节点的深度

使用广度优先搜索的思想,用队列存储每一层节点

DFS代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:def maxDepth(self, root) -> int:if not root:return 0stack = []height = 0current = rootmax_height = 0while current or stack:while current:height+=1stack.append((current, height))current = current.leftmax_height = max(height, max_height)current = stack[-1][0]height = stack[-1][1]stack.pop()current = current.rightreturn max_height

这里可以使用递归的思想来做深度优先搜索

递归DFS代码:

class Solution:def maxDepth(self, root) -> int:if not root:return 0else:left_height = self.maxDepth(root.left)right_height = self.maxDepth(root.right)return max(left_height, right_height)+1

BFS代码:

import queue
class Solution:def maxDepth(self, root) -> int:if not root:return 0tree_queue = queue.Queue()height = 0tree_queue.put(root)while not tree_queue.empty():length = tree_queue.qsize()while length>0:current = tree_queue.get()if current.left:tree_queue.put(current.left)if current.right:tree_queue.put(current.right)length-=1height+=1return height

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com