104.二叉树的最大深度
题目链接:104. 二叉树的最大深度 - 力扣(LeetCode)
class Solution {
public int maxDepth(TreeNode root) {
return (root == null) ? 0: Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
}
111.二叉树的最小深度
题目链接:111. 二叉树的最小深度 - 力扣(LeetCode)
class Solution {
public int minDepth(TreeNode root) {
if(root == null) {
return 0;
}
return helper(root);
}
private int helper(TreeNode root) {
if(root.left == null && root.right == null) {
return 1;
}
if(root.left != null && root.right != null) {
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
if(root.left == null) {
return minDepth(root.right) + 1;
}
return minDepth(root.left) + 1;
}
}
222.完全二叉树的节点个数
题目链接:222. 完全二叉树的节点个数 - 力扣(LeetCode)
class Solution {
public int countNodes(TreeNode root) {
if(root == null) {
return 0;
}
int lh = leftHeight(root), rh = rightHeight(root);
if(lh == rh) {
return (1 << lh) - 1;
}else {
return 1 + countNodes(root.left) + countNodes(root.right);
}
}
private int leftHeight(TreeNode root) {
int level = 0;
while (root != null) {
root = root.left;
++level;
}
return level;
}
private int rightHeight(TreeNode root) {
int level = 0;
while(root != null) {
root = root.right;
++level;
}
return level;
}
}