104.二叉树的最大深度
题目链接
题目描述
二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
思路
二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数或者节点数(取决于高度从0开始还是从1开始)
而根节点的高度就是二叉树的最大深度,所以本题中我们通过后序求的根节点高度来求的二叉树最大深度。
实现代码
class Solution {
public int maxDepth(TreeNode root) {
return getdepth(root);
}
public int getdepth(TreeNode node) {
if (node == null) return 0;
int leftdepth = getdepth(node.left);// 左
int rightdepth = getdepth(node.right);// 右
int depth = 1 + Math.max(leftdepth, rightdepth);// 中
return depth;
}
}
//精简代码
class solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDepth = maxDepth(root.left);
int rightDepth = maxDepth(root.right);
return Math.max(leftDepth, rightDepth) + 1;
}
}
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;
}
// 左右结点都不为null
return Math.min(leftDepth, rightDepth) + 1;
}
}
222.完全二叉树的节点个数
题目链接
题目描述
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
思路
这道题目的递归法和求二叉树的深度写法类似。
递归遍历的顺序依然是后序(左右中)。
实现代码
class Solution {
public int countNodes(TreeNode root) {
if(root == null) {
return 0;
}
return countNodes(root.left) + countNodes(root.right) + 1;
}
}