一、题目描述:
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例: 给定二叉树 [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7返回它的最大深度 3 。
题目链接:104. 二叉树的最大深度
二、思路分析:
- 二叉树的最大深度可以使用深度优先遍历来确定;
- 空的二叉树深度为0;普通情况使用递归深度遍历根结点的左右子树的值并加1,即为所求。
三、AC 代码:
class Solution {
var maxDeepValue : Int = 0;
func maxDepth(_ root: TreeNode?) -> Int {
if (root == nil) {
// 空树
return 0;
}
// 后边的 +1 是加的根节点的层级
let leftDeepValue : Int = maxDepth(root?.left) + 1;
let rightDeepValue : Int = maxDepth(root?.right) + 1;
maxDeepValue = leftDeepValue;
if (rightDeepValue > maxDeepValue) {
maxDeepValue = rightDeepValue;
}
return maxDeepValue;
}
}
四、参考学习网址
本文正在参与「掘金 3 月闯关活动」, 点击查看 活动详情