描述
給定一個(gè)二叉樹,找出其最大深度。
二叉樹的深度為根節(jié)點(diǎn)到最遠(yuǎn)葉子節(jié)點(diǎn)的距離。
樣例
給出一棵如下的二叉樹:
1
/ \
2 3
/ \
4 5
這個(gè)二叉樹的最大深度為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.
*/
// 定義全局變量,因?yàn)?maxDepth 方法和 helper 方法是并列方法,如果把depth定義在 maxDepth 中,helper是沒辦法調(diào)用 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 時(shí)(即 root 是葉子結(jié)點(diǎn)) 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;
}
}