题目
再写个简单题爽爽
题目链接
题解
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
return dfs(root);
}
/**
* 方法返回当前节点之下(包含当前节点)一共有几层
*/
private int dfs(TreeNode node) {
// 当前节点也是空返回0
if (node == null) {
return 0;
}
// 左右子树都为空返回1
if (node.left == null && node.right == null) {
return 1;
}
// 左子树和右子树取个最大值再加上本层
return Math.max(dfs(node.left), dfs(node.right)) + 1;
}
}