1.题目描述
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
2.思路
这个二叉树的结构如下:
根节点 1
左子节点 2
右子节点 3
左子节点 4
计算过程
从根节点 1 开始计算:
计算左子树的最大深度:
根节点 2:
左子树为空,深度为0。
右子树为空,深度为0。
所以节点 2 的深度为 Math.max(0, 0) + 1 = 1。
计算右子树的最大深度:
根节点 3:
计算左子树的最大深度:
根节点 4:
左子树为空,深度为0。
右子树为空,深度为0。
所以节点 4 的深度为 Math.max(0, 0) + 1 = 1。
右子树为空,深度为0。
所以节点 3 的深度为 Math.max(1, 0) + 1 = 2。
最后,根节点 1 的深度为 Math.max(1, 2) + 1 = 3。
3.代码实现
/**
* 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) {
if(root==null)
{
return 0;
}
int leftDepth=maxDepth(root.left);
int rightDepth=maxDepth(root.right);
return Math.max(leftDepth,rightDepth)+1;
}
}