二叉树的深度
二叉树
题目
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
提示:
节点总数 <= 10000
注意:本题与主站 104 题相同:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/
Related Topics
树
深度优先搜索
广度优先搜索
二叉树
👍 248
👎 0
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
}
}
思路
- 层序遍历
- 累加器
实现
class Solution {
public int maxDepth(TreeNode root) {
if (root==null) return 0;
int[] res= new int[1];
method(root,1,res);
return res[0]-1;
}
public void method(TreeNode node, int level, int[] res){
if (node==null)return;
method(node.left,level+1,res);
method(node.right,level+1,res);
++level;
if (level>res[0]){
res[0]=level;
}
}
}
结果
解答成功:
执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:40.3 MB,击败了88.19% 的Java用户