代码随想录算法训练营Day16 | 104.二叉树的最大深度 559.n叉树的最大深度 111.二叉树的最小深度 222.完全二叉树的节点个数
LeetCode 104.二叉树的最大深度
思路:
递归法与层序法
//递归法
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
};
//层序法
class Solution {
public:
int maxDepth(TreeNode* root) {
queue<TreeNode*> que;
if(!root) return 0;
que.push(root);
int depth = 0;
while(!que.empty()){
int size = que.size();
depth++;
for(int i=0; i<size; i++){
TreeNode* node = que.front();
que.pop();
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
}
return depth;
}
};
LeetCode 559.n叉树的最大深度
思路:
递归和层序
//递归
class Solution {
public:
int maxDepth(Node* root) {
if(!root) return 0;
int depth = 0;
for(Node* node:root->children){
depth = max(depth,maxDepth(node));
}
return depth+1;
}
};
注意 :
- 注意depth初始值为0;
LeetCode 111.二叉树的最小深度
思路:
判断递归的三种情况
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
else if(!root->left&&root->right) return minDepth(root->right)+1;
else if(!root->right&&root->left) return minDepth(root->left)+1;
else return 1+min(minDepth(root->left), minDepth(root->right));
}
};
LeetCode 222.完全二叉树的节点个数
思路:
递归和层序
//递归
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
return 1+countNodes(root->left)+countNodes(root->right);
}
};
//层序
class Solution {
public:
int countNodes(TreeNode* root) {
queue<TreeNode*> que;
int count = 0;
if (root) que.push(root);
while(!que.empty()){
int size = que.size();
for (int i = 0; i < size; i++){
TreeNode* node = que.front();
que.pop();
count++;
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
}
return count;
}
};