Leetcode 104 二叉树的最大深度(Maximum Depth of Binary Tree) 题解分析
题目介绍
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
代码
// 主体是个递归的应用
public int maxDepth(TreeNode root) {
// 节点的退出条件之一
if (root == null) {
return 0;
}
int left = 0;
int right = 0;
// 存在左子树,就递归左子树
if (root.left != null) {
left = maxDepth(root.left);
}
// 存在右子树,就递归右子树
if (root.right != null) {
right = maxDepth(root.right);
}
// 前面返回后,左右取大者
return Math.max(left + 1, right + 1);
}
分析
其实对于树这类题,一般是以递归形式比较方便,只是要注意退出条件