版權(quán)聲明:本文為博主原創(chuàng)文章晒喷,未經(jīng)博主允許不得轉(zhuǎn)載。
難度:容易
要求:
給定一個二叉樹,找出其最大深度链快。二叉樹的深度為根節(jié)點到最遠葉子節(jié)點的距離。
樣例給出一棵如下的二叉樹:
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.
*/
public int maxDepth(TreeNode root) {
// write your code here
if (root == null) {
return 0;
}
return getMax(root);
}
private int getMax(TreeNode node){
if (node == null) {
return Integer.MIN_VALUE;
}
if (node.left == null && node.right == null) {
return 1;
}
return Math.max(getMax(node.left), getMax(node.right)) + 1;
}
}