104. Maximum Depth of Binary Tree
104. Maximum Depth of Binary Tree
Easy
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its depth = 3.
对于给定的1个结点,如果不为空,那么depth就为1。
然后需要遍历左右子结点,分别得到depth,并且取其中较大的值。
只要左右子结点,有一个不为空,那就递归遍历。
public int MaxDepth(TreeNode root) { int depth; if (root == null) { depth = 0; } else { depth = 1; TreeNode left = root.left; TreeNode right = root.right; if (left != null || right != null) { int leftDepth = MaxDepth(left); int rightDepth = MaxDepth(right); depth = depth + Math.Max(leftDepth, rightDepth); } } return depth; }
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2016-03-18 ASP.NET MVC 4 Content Map
2016-03-18 ASP.NET Overview
2016-03-18 ASP.NET 4 and Visual Studio 2010
2015-03-18 QuickStart下的CommandFilter项目 github上自己修改过的版本
2015-03-18 演练:实现支持基于事件的异步模式的组件