1.二叉树的最大深度
题目链接/文章讲解/视频讲解: 代码随想录
代码:后序遍历(详细版)
class Solution {
public:
int maxDepth(TreeNode* root) {
// 最大深度就是根结点的高度
// 递归出口
if(root == NULL) return 0;
// 左
int leftHeight = maxDepth(root->left);
// 右
int rightHeight = maxDepth(root->right);
// 中
int result = leftHeight > rightHeight ? leftHeight : rightHeight;
return result + 1;
}
};
(精简版)
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == NULL) return 0;
return 1 + max(maxDepth(root->left),maxDepth(root->right));
}
};
其中的max库函数来自<algorithm>头文件
2.n叉树的最大深度
class Solution {
public:
int maxDepth(Node* root) {
if(root == NULL) return 0;
int depth = 0;
for(int i = 0;i < root->children.size();i++){
depth = max(depth,maxDepth(root->children[i]));
}
return depth + 1;
}
};
状态:总是忘记最后返回的是最大值加一。以后写代码时,把遍历顺序写出来,就不会忘记中的处理逻辑。
3.二叉树的最小深度
题目链接/文章讲解/视频讲解: 代码随想录
代码:后序遍历
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 leftHeight + 1;
if(root->right != NULL && root->left == NULL) return rightHeight + 1;
// 处理逻辑
return 1 + min(leftHeight,rightHeight);
}
};
4.完全二叉树的结点数量
题目链接/文章讲解/视频讲解: 代码随想录
class Solution {
public:
int countNodes(TreeNode* root) {
// 终止条件
// 结点为空时
if(root == NULL) return 0;
// 遇到满二叉树的情况时
TreeNode* left = root->left;
TreeNode* right = root->right;
int leftHeight = 0;
int rightHeight= 0;
while(left != NULL){
leftHeight++;
left = left->left;
}
while(right != NULL){
rightHeight++;
right = right->right;
}
if(leftHeight == rightHeight) return (2<<leftHeight) - 1;
// 左
int leftnum = countNodes(root->left);
// 右
int rightnum = countNodes(root->right);
// 中
return 1 + leftnum + rightnum;
}
};
思路:难点在想到,完全二叉树总是可以找到满二叉树的子树,这样利用了完全二叉树的特性,减少了遍历的结点数(只需要判断左右孩子的深度是不是相等)