104. 二叉树的最大深度
思路:后序遍历求的根节点高度来求的二叉树最大深度
class Solution {
public int maxDepth(TreeNode root) {
if(root == null) {
return 0;
}
return 1 + Math.max(getDepth(root.left), getDepth(root.right));
}
public int getDepth(TreeNode node) {
if(node == null) {
return 0;
}
int leftDepth = getDepth(node.left);
int rightDepth = getDepth(node.right);
return 1 + Math.max(leftDepth, rightDepth);
}
}
小结:值得注意的点
- 区分二叉树节点的深度和高度:深度是指从根节点到该节点的最长简单路径边的条数或者节点数,而高度是指从该节点到叶子节点的最长简单路径边的条数后者节点数
- 单层递归的逻辑:求左右子树的最大深度,然后取最大的
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 1 + depth;
}
}
小结:值得注意的点
- 需要注意递归中depth的求法,与求二叉树的最大深度不同,此处需要对N叉树中节点的所有孩子进行长度的比较
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) {
return rightDepth + 1;
}
if(root.right == null) {
return leftDepth + 1;
}
return 1 + Math.min(leftDepth, rightDepth);
}
}
小结:值得注意的点
- 最小深度容易误解,如下图所示:根节点的最小深度不是1而是3,因为题目中对最小深度的定义是从根节点到叶子节点的距离
- 单层递归逻辑:如果左子树为空,右子树不为空,说明最小深度是 1 + 右子树的深度。反之,右子树为空,左子树不为空,最小深度是 1 + 左子树的深度。 最后如果左右子树都不为空,返回左右子树深度最小值 + 1
222. 完全二叉树的节点个数
思路:可以使用递归和迭代法。迭代法主要是利用层序遍历来统计每一层的节点个数,并将每层的节点数相加便可以得到最终整课完全二叉树的节点个数。
递归:
class Solution {
public int countNodes(TreeNode root) {
if(root == null) {
return 0;
}
return getNodesNum(root);
}
public int getNodesNum(TreeNode node) {
if(node == null) {
return 0;
}
int leftNodesNum = getNodesNum(node.left);
int rightNodesNum = getNodesNum(node.right);
return 1 + leftNodesNum + rightNodesNum;
}
}
迭代:
class Solution {
public int countNodes(TreeNode root) {
Queue<TreeNode> queue = new LinkedList();
int result = 0;
if(root == null) {
return result;
}
queue.add(root);
while(!queue.isEmpty()) {
int size = queue.size();
while(size > 0) {
TreeNode node = queue.poll();
result++;
size--;
if(node.left != null) {
queue.add(node.left);
}
if(node.right != null) {
queue.add(node.right);
}
}
}
return result;
}
}
小结:值得注意的点
- 递归返回条件的理解:节点的左孩子为空会返回0,节点的右孩子为空会返回0,而此时需要统计节点本身的数量,则最终返回的是0+0+1=1