1.1 问题描述
1.2 问题分析
1.3 问题解决
/**
* 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) {
if(root == nullptr) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
2.1 问题描述
2.2 问题分析
2.3 问题解决
/**
* 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) {
if(root == nullptr) return 0;
int m1 = minDepth(root->left);
int m2 = minDepth(root->right);
return root->left == nullptr || root->right == nullptr
? m1 + m2 + 1 : min(m1, m2) + 1;
}
};
3.1 问题描述
3.2 问题分析
3.3 问题解决
/**
* 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) {
vector<vector<int>> level;
queue<TreeNode*> q;
if(root != nullptr) q.push(root);
else return 0;
while(!q.empty())
{
int n = q.size();
vector<int> v;
for(int i = 0; i < n; i++)
{
TreeNode* node = q.front();
q.pop();
v.push_back(node->val);
if(node->left != nullptr) q.push(node->left);
if(node->right != nullptr) q.push(node->right);
}
level.push_back(v);
}
return pow(2, level.size()-1) - 1 + level[level.size()-1].size();
}
};