- 二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
实现思路:
通过递归完成,一棵二叉树的深度就是左右子树的深度的最大值 加上一
最后得到结果
代码:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
//左子树深度 和 右子树深度 的最大值 + 1
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}