104.二叉树的最大深度
//层序遍历法
// class Solution {
// public:
// int maxDepth(TreeNode* root) {
// int ans = 0;
// queue<TreeNode*> q;
// if(root == nullptr) return 0;
// q.push(root);
// while(!q.empty()){
// int size = q.size();
// while(size--){
// TreeNode* cur = q.front();
// q.pop();
// if(cur->left) q.push(cur->left);
// if(cur->right) q.push(cur->right);
// }
// ans++;
// }
// return ans;
// }
// };
//递归法,后序遍历
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == nullptr) return 0;
int left_h = maxDepth(root->left);
int right_h = maxDepth(root->right);
return 1+ max(left_h,right_h);
}
};
559.n叉树的最大深度
class Solution {
public:
int maxDepth(Node* root) {
if(root == nullptr) return 0;
vector<Node*> chil = root->children;
int d_max = 0;
for(Node* c : chil){
if(c != nullptr){
d_max = max(d_max,maxDepth(c));
}
}
return d_max + 1;
}
};
111.二叉树的最小深度
//层序遍历法
// class Solution {
// public:
// int minDepth(TreeNode* root) {
// int ans = 0;
// queue<TreeNode*> q;
// if(root == nullptr) return 0;
// q.push(root);
// while(!q.empty()){
// int size = q.size();
// while(size--){
// TreeNode* cur = q.front();
// q.pop();
// if(cur->left) q.push(cur->left);
// if(cur->right) q.push(cur->right);
// if(cur->left == nullptr && cur->right == nullptr)return ans+1;
// }
// ans++;
// }
// return ans;
// }
// };
//递归法,后序遍历
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == nullptr) return 0;
int left_h = minDepth(root->left);
int right_h = minDepth(root->right);
if(root->left == nullptr && root->right != nullptr) return 1 + right_h;
if(root->right == nullptr && root->left != nullptr) return 1 + left_h;
return 1 + min(left_h,right_h);
}
};
222.完全二叉树的节点个数
//递归法
class Solution {
public:
int countNodes(TreeNode* root) {
if(root == nullptr) return 0;
int left_num = countNodes(root->left);
int right_num = countNodes(root->right);
return left_num + right_num + 1;
}
}
//层序遍历
class Solution {
public:
int countNodes(TreeNode* root) {
int ans = 0;
queue<TreeNode*> q;
if(root == nullptr) return 0;
q.push(root);
while(!q.empty()){
int size = q.size();
while(size--){
ans++;
TreeNode* cur = q.front();
q.pop();
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
}
}
return ans;
}
};
//用完全二叉树特性做优化
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; // 这里初始为0是有目的的,为了下面求指数方便
while (left) { // 求左子树深度
left = left->left;
leftDepth++;
}
while (right) { // 求右子树深度
right = right->right;
rightDepth++;
}
if (leftDepth == rightDepth) {
return (2 << leftDepth) - 1; // 注意(2<<1) 相当于2^2,所以leftDepth初始为0
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
};
总结
题型:二叉树的最大深度,最小深度,节点个数
技巧:后序遍历求解,注意最小深度的特殊情况。