题意

计算二叉树的深度

题目来源:https://leetcode.com/problems/maximum-depth-of-binary-tree/

标记难度:Easy

提交次数:思路很乱,参考 Discuss 的答案

代码效率:100.00%

分析

递归左右子树,对深度最大的子树进行递归调用并+1

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 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) {
if(root == null){
return 0;
}
return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
}
}