給定一個(gè)二叉樹,找出其最大深度弦追。
二叉樹的深度為根節(jié)點(diǎn)到最遠(yuǎn)葉子節(jié)點(diǎn)的最長路徑上的節(jié)點(diǎn)數(shù)捂龄。
說明: 葉子節(jié)點(diǎn)是指沒有子節(jié)點(diǎn)的節(jié)點(diǎn)漆诽。
示例:
給定二叉樹 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 扮休。
解法1:
思路: 思路很簡單迎卤,使用遞歸的方法,往下搜索玷坠,直到最后左右兒子都為null蜗搔。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
return root==null ? 0 :(1+ Math.max(maxDepth(root.left),maxDepth(root.right)));
}
}
思考一下: 搜給定一個(gè)二叉樹,找出其最小深度八堡。
解法:
思路:使用遞歸樟凄,跟上面解法同一道理。
public int minDepth(TreeNode root){
if(root== null){
return 0;
}
if(root.left==null && root.right==null){
return 1;
}
if(root.left==null){
return 1+Math.min(minDepth(root.right));
}else if(root.right==null){
return 1+Math.min(minDepth(root.left));
}else{
return 1+Math.min(minDepth(root.left),minDepth(root.right));
}
}
}