104.二叉树的最大深度 (优先掌握递归)
题目链接/文章讲解/视频讲解: 代码随想录
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == nullptr) return 0;
int depth = 1;
depth = traversal(root, depth);
return depth;
}
int traversal(TreeNode* cur, int depth){
if(cur == nullptr) return depth - 1;
return max(traversal(cur->left, depth + 1),traversal(cur->right, depth + 1));
}
};
111.二叉树的最小深度 (优先掌握递归)
题目链接/文章讲解/视频讲解:代码随想录
层序遍历
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == nullptr) return 0;
queue<TreeNode*> que;
int queSize;
int depth = 0;
TreeNode*temp;
que.emplace(root);
while(!que.empty()){
queSize = que.size();
depth++;
for(int i = 0; i < queSize; i++){
temp = que.front();
que.pop();
if(temp->left == nullptr && temp->right == nullptr) return depth;
else{
if(temp->left != nullptr) que.emplace(temp->left);
if(temp->right != nullptr) que.emplace(temp->right);
}
}
}
return 10086;
}
};
222.完全二叉树的节点个数(优先掌握递归)
题目链接/文章讲解/视频讲解:代码随想录
利用完全二叉树性质
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;
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
};