class Solution {
public:
int ans = 0;
void sh(TreeNode* a, int l) {
if (l > ans)
ans = l;
if (a->left == NULL && a->right == NULL)
return;
if (a->left != NULL) {
l++;
sh(a->left, l);
l--;
}
if (a->right != NULL) {
l++;
sh(a->right, l);
l--;
}
}
int maxDepth(TreeNode* root) {
if(root==NULL)
return 0;
sh(root, 1);
return ans;
}
};
559.n叉树的最大深度
class Solution {
public:
int maxDepth(Node* root) {
queue<Node*> a;
int ans = 0;
if (root != NULL)
a.push(root);
while (!a.empty()) {
int size = a.size();
for (int i = 0; i < size; i++) {
Node* cur = a.front();
a.pop();
for(auto j:cur->children){
a.push(j);
}
}
ans++;
}
return ans;
}
};
111.二叉树的最小深度
class Solution {
public:
int minDepth(TreeNode* root) {
queue<TreeNode*>a;
int ans=1;
if(root!=NULL)
a.push(root);
else
return 0;
while(!a.empty()){
int size=a.size();
for(int i=0;i<size;i++){
TreeNode* cur=a.front();
a.pop();
if(!cur->right&&!cur->left)
return ans;
if(cur->right)
a.push(cur->right);
if(cur->left)
a.push(cur->left);
}
ans++;
}
return ans;
}
};
222.完全二叉树的节点个数
class Solution {
public:
int countNodes(TreeNode* root) {
queue<TreeNode*> a;
int ans = 0;
if (root != NULL)
a.push(root);
while (!a.empty()) {
int size = a.size();
for (int i = 0; i < size; i++) {
TreeNode* cur = a.front();
a.pop();
if (cur->left)
a.push(cur->left);
if (cur->right)
a.push(cur->right);
}
ans = ans + size;
}
return ans;
}
};