描述
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的距离。
样例
给出一棵如下的二叉树:
1
/ \
2 3
/ \
4 5
这个二叉树的最大深度为3.
代码
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
- 遍历
public class Solution {
/**
* @param root: The root of binary tree.
* @return: An integer.
*/
// 定义全局变量,因为 maxDepth 方法和 helper 方法是并列方法,如果把depth定义在 maxDepth 中,helper是没办法调用 depth 变量的
private int depth;
public int maxDepth(TreeNode root) {
depth = 0;
helper(root, 1);
return depth;
}
private void helper(TreeNode root, int curDepth) {
// 递归出口
if (root == null) {
return;
}
if (curDepth > depth) {
depth = curDepth;
}
// 递归的分解,每向下一层,深度要加1
// root.left、root.right 为 0 时(即 root 是叶子结点) curDepth + 1 不生效
helper (root.left, curDepth + 1);
helper (root.right, curDepth + 1);
}
}
- 分治
public class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return Math.max(left, right) + 1;
}
}