代码随想录算法训练营第十六天| 104.二叉树的最大深度、111.二叉树的最小深度、222.完全二叉树的节点个数
104.二叉树的最大深度
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
int ans = 0;
queue<TreeNode*> que;
TreeNode* node;
if (root)
que.push(root);
while (!que.empty()) {
int size = que.size();
while (size--) {
node = que.front();
que.pop();
if (node->left)
que.push(node->left);
if (node->right)
que.push(node->right);
}
ans++;
}
return ans;
}
};
111.二叉树的最小深度
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
queue<TreeNode*> que;
TreeNode* node;
int depth = 0;
if (root)
que.push(root);
while (!que.empty()) {
depth++;
int size = que.size();
while (size--) {
node = que.front();
que.pop();
if (!node->left && !node->right)
return depth;
if (node->left)
que.push(node->left);
if (node->right)
que.push(node->right);
}
}
return depth;
}
};
222.完全二叉树的节点个数
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if (!root)
return 0;
TreeNode* left = root->left;
TreeNode* right = root->right;
int leftDepth = 1, rightDepth = 1;
while (left)
left = left->left, leftDepth++;
while (right)
right = right->right, rightDepth++;
if (leftDepth == rightDepth)
return (1 << leftDepth) - 1;
return countNodes(root->left) + countNodes(root->right) + 1;
}
};