二叉树的最大深度
题目链接:力扣
二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数或者节点数(取决于深度从0开始还是从1开始)
二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数或者节点数(取决于高度从0开始还是从1开始)
所以 二叉树的最大深度 = 根节点高度
单层递归的逻辑:先求它的左子树的深度,再求右子树的深度,最后取左右深度最大的数值 再+1 (加1是因为算上当前中间节点)就是目前节点为根节点的树的深度。
class solution {
public:
int getdepth(TreeNode* node) {
if (node == NULL) return 0;
int leftdepth = getdepth(node->left); // 左
int rightdepth = getdepth(node->right); // 右
int depth = 1 + max(leftdepth, rightdepth); // 中
return depth;
}
int maxDepth(TreeNode* root) {
return getdepth(root);
}
};
如果想用迭代法,可以参考昨天博客中的层序遍历。
n叉树的最大深度
题目链接:力扣
整体思路与上题类似
class Solution {
public:
int maxDepth(Node* root) {
if (root == nullptr)
return 0;
int depth = 0;
for(int i=0;i<root->children.size();i++)
{
depth = max(depth,maxDepth(root->children[i]));
}
return depth+1;
}
};
二叉树的最小深度
题目链接:力扣
最小深度是从根节点到最近叶子节点的最短路径上的节点数量
而叶子节点是 左右孩子都为空的节点。
class Solution {
public:
int getDepth(TreeNode* node) {
if (node == NULL) return 0;
int leftDepth = getDepth(node->left); // 左
int rightDepth = getDepth(node->right); // 右
// 中
// 当一个左子树为空,右不为空,这时并不是最低点
if (node->left == NULL && node->right != NULL) {
return 1 + rightDepth;
}
// 当一个右子树为空,左不为空,这时并不是最低点
if (node->left != NULL && node->right == NULL) {
return 1 + leftDepth;
}
int result = 1 + min(leftDepth, rightDepth);
return result;
}
int minDepth(TreeNode* root) {
return getDepth(root);
}
};
完全二叉树的节点个数
题目链接:力扣
其实这题可以直接用遍历的方法求节点数,但是这样没有用上完全二叉树的性质
判断其子树是不是满二叉树,如果是,则利用公式计算这个满二叉树的节点数量,如果不是则继续递归
class Solution {
public:
int countNodes(TreeNode* root) {
if (root == nullptr) return 0;
TreeNode* left = root->left;
TreeNode* right = root->right;
int leftDepth = 0, rightDepth = 0;
while (left) { // 求左子树深度
left = left->left;
leftDepth++;
}
while (right) { // 求右子树深度
right = right->right;
rightDepth++;
}
if (leftDepth == rightDepth) {
return (2 << leftDepth) - 1; // 注意(2<<1) 相当于2^2,所以leftDepth初始为0
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
};