104. 代码随想录
//递归方法
class Solution {
public int maxDepth(TreeNode root) {
return getDept(root);
}
public int getDept(TreeNode root){
if(root == null){
return 0;
}
int left = getDept(root.left);
int right = getDept(root.right);
return Math.max(left,right) + 1;
}
}
111. 力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
class Solution {
public int minDepth(TreeNode root) {
return getDept(root);
}
public int getDept(TreeNode root){
if(root == null){
return 0;
}
int leftDepth = getDept(root.left); // 左
int rightDepth = getDept(root.right); // 右
if(root.left==null && root.right != null){
return 1 + rightDepth;
}
if(root.left != null && root.right == null){
return 1 + leftDepth;
}
return 1+ Math.min(leftDepth,rightDepth);
}
}
222 力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
class Solution {
public int countNodes(TreeNode root) {
return count(root);
}
public int count(TreeNode root){
if(root == null){
return 0;
}
int left = count(root.left);
int right = count(root.right);
return left + right + 1;
}
}