您的位置:首页 > 其它

LeetCode 104 二叉树的最大深度

2019-06-08 12:00 344 查看

题目描述

给定一个二叉树,找出其最大深度。

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

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

3
/ \
9  20
/  \
15   7

返回它的最大深度 3 。

分析

DFS策略。

DFS

沿着树的深度遍历树的节点,尽可能深的搜索树的分支。More:https://zh.wikipedia.org/wiki/%E6%B7%B1%E5%BA%A6%E4%BC%98%E5%85%88%E6%90%9C%E7%B4%A2

代码

class Solution {
public int maxDepth(TreeNode root) {
int cnt = 0;
if (root == null) return cnt;
TreeNode p = root.left;
TreeNode q = root.right;
cnt = java.lang.Math.max(maxDepth(p), maxDepth(q));
return ++cnt;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: