class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}else{
int leftheight = maxDepth(root.left);
int rightheight = maxDepth(root.right);
return Math.max(leftheight,rightheight)+1;
}
}
}
对于递归的理解还很浅,总是思路差不多是对的,但就是差一些。
class Solution {
public int minDepth(TreeNode root) {
if(root==null){
return 0;
}
int leftDepth = minDepth(root.left);
int rightDepth = minDepth(root.right);
if(root.left==null){
return rightDepth+1;
}
if(root.right==null){
return leftDepth+1;
}
return Math.min(leftDepth,rightDepth)+1;
}
}
代码随想录的解析很清晰,
- 确定递归函数的参数和返回值
- 确定终止条件
- 确定单层递归的逻辑 求二叉树的最小深度和求二叉树的最大深度的差别主要在于处理左右孩子不为空的逻辑。
class Solution {
int count = 0;
public int countNodes(TreeNode root) {
if(root==null){
return 0;
}
if(root.left!=null){
count = countNodes(root.left);
}
count++;
if(root.right!=null){
count = countNodes(root.right);
}
return count;
}
}