104.二叉树的最大深度
104. 二叉树的最大深度
- 第一想法:自底向上遍历
- 看到题解想法:同上
- 遇到困难:无
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
}
559.n叉树的最大深度
559. N 叉树的最大深度
- 第一想法:自底向上遍历
- 看到题解想法:同上
- 遇到困难:解法同题1
class Solution {
public int maxDepth(Node root) {
if (root == null) return 0;
int maxSize = 0;
for(Node n: root.children) {
maxSize = Math.max(maxSize, maxDepth(n));
}
return maxSize + 1;
}
}
111.二叉树的最小深度(易出错)
111. 二叉树的最小深度
- 第一想法:本来尝试使用与题2相同解法,但是会将空子树也记录下来。
- 看到题解想法:我们需要使用额外条件去处理当前节点其中一个子树为空的情况
- 遇到困难:要从叶子节点开始计算。如果根节点的左子树是null,不能从左子树开始算。
class Solution {
//要明确:叶子节点才能计算长度
public int minDepth(TreeNode root) {
if (root == null) return 0;
// 当前节点只有1个子树:直接遍历此子树
if (root.left != null && root.right == null) return minDepth(root.left) + 1;
if (root.left == null && root.right != null) return minDepth(root.right) + 1;
// 当前节点有2个子树 or 无子树(叶子节点):比较两子树size大小
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}
}
222.完全二叉树的节点个数
222. 完全二叉树的节点个数
- 第一想法:自底向上计算节点个数
- 看到题解想法:没有利用到完全二叉树的特性。题解分别遍历左右子树而判断是否是完全二叉树,然后使用2^n - 1计算。
- 遇到困难:本题仍然使用了普遍的二叉树遍历方法,因为简单通用。
public int countNodes(TreeNode root) {
if (root == null) return 0;
return countNodes(root.left) + countNodes(root.right) + 1;
}