104.二叉树的最大深度
思路:递归法,采用后序遍历计算树的高度。先求左子树的深度,再求右子树的深度,最后取左右深度最大的数值再+1(中间节点) ,得到根节点的树的深度。
class Solution {
public int maxDepth(TreeNode root) {
if(root == null){
return 0;
}
int leftHeight = maxDepth(root.left);
int rightHeight = maxDepth(root.right);
int height = 1+Math.max(leftHeight,rightHeight);
return height;
}
}
559.n叉树的最大深度
class Solution {
public int maxDepth(Node root) {
if (root == null) return 0;
int depth = 0;
if (root.children != null){
for (Node child : root.children){
depth = Math.max(depth, maxDepth(child));
}
}
return depth + 1;
}
}
111.二叉树的最小深度
思路:最小深度与最大深度不同之处在于,最小深度需要考虑左右子树为空的情况。左子树为空,右子树不为空,说明最小深度是 1 + 右子树的深度;右子树为空,左子树不为空,最小深度是 1 + 左子树的深度。如果左右子树都不为空,返回左右子树深度最小值 + 1 。
class Solution {
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
int leftHeight = minDepth(root.left);
int rightHeight = minDepth(root.right);
if(root.left != null && root.right == null){
return 1 + leftHeight;
}
if(root.left == null && root.right != null){
return 1 + rightHeight;
}
int result = 1+Math.min(leftHeight,rightHeight);
return result;
}
}
222.完全二叉树的节点个数
思路:分两种情况。满二叉树,可以直接用 2^树深度 - 1 来计算;最后一层叶子节点未满,可以分别递归左孩子和右孩子,递归到某一深度一定会有左孩子或者右孩子为满二叉树,回到第一种。
class Solution {
public int countNodes(TreeNode root) {
if (root == null) return 0;
TreeNode left = root.left;
TreeNode right = root.right;
int leftDepth = 0, rightDepth = 0;
while (left!=null) {
left = left.left;
leftDepth++;
}
while (right!=null) {
right = right.right;
rightDepth++;
}
if (leftDepth == rightDepth) {
return (2 << leftDepth) - 1;
}
int leftNum = countNodes(root.left);
int rightNum = countNodes(root.right);
int result = 1+leftNum+rightNum;
return result;
}
}