题号:剑指 Offer 55 - I
题目名:二叉树的深度
原题URL:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/
题目描述
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
示例
示例 1:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
限制
节点总数 <= 10000
思路
1.递归,如果当前结点为空,返回0,否则返回当前结点1+左子树和右子树的最大深度
解题代码
class Solution {
public int maxDepth(TreeNode root) {
if(root==null) return 0;
return 1+Math.max(maxDepth(root.left),maxDepth(root.right));
}
}