改用递归,多熟悉
104.二叉树的最大深度
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftHeight = maxDepth(root.left);
int rightHeight = maxDepth(root.right);
return Math.max(leftHeight, rightHeight) + 1;
}
}
111.二叉树的最小深度
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftMin = minDepth(root.left);
int rightMin = minDepth(root.right);
if (leftMin == 0 && rightMin == 0) {
return 1;
} else if (leftMin == 0) {
return rightMin + 1;
} else if (rightMin == 0) {
return leftMin + 1;
} else {
return Math.min(leftMin, rightMin) + 1;
}
}
}
222.完全二叉树的节点个数
class Solution {
public int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
int leftCount = countNodes(root.left);
int rightCount = countNodes(root.right);
return leftCount + rightCount+1;
}
}