104.二叉树的最大深度 111.二叉树的最小深度 222.完全二叉树的节点个数
104.二叉树的最大深度
class Solution {
//使用递归来解决,后序遍历来做
public int maxDepth(TreeNode root) {
if (root == null) return 0;
int leftHeight = maxDepth(root.left);
int rightHeight = maxDepth(root.right);
return 1 + Math.max(leftHeight, rightHeight);
}
}
111.二叉树的最小深度
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 && root.right != null) return 1 + rightDepth;
if (root.right == null && root.left != null) return 1 + leftDepth;
return Math.min(leftDepth, rightDepth) + 1;
}
}
222.完全二叉树的节点个数
class Solution {
public int countNodes(TreeNode root) {
if (root == null) return 0;
int leftNumber = countNodes(root.left);
int rightNumber = countNodes(root.right);
return leftNumber + rightNumber + 1;
}
}
总结
递归好难!!!