104.二叉树的最大深度
重点递归
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
}
111.二叉树最小深度
class Solution {
public int minDepth(TreeNode root) {
if(root == null)return 0;
if(root.left == null){
return minDepth(root.right)+1;
}else if(root.right == null){
return minDepth(root.left)+1;
}else{
return Math.min(minDepth(root.left),minDepth(root.right))+1;
}
}
}
222.完全二叉树节点个数
class Solution {
public int countNodes(TreeNode root) {
if(root == null)return 0;
TreeNode left = root.left;
TreeNode right = root.right;
int leftdepth = 0;
int rightdepth = 0;
while(left!=null){
leftdepth++;
left=left.left;
}
while(right!=null){
rightdepth++;
right = right.right;
}
if(leftdepth == rightdepth){
return (2<<leftdepth)-1;
}
return countNodes(root.left)+countNodes(root.right)+1;
}
}