LeetCode104.二叉树的最大深度
/**
* 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) {
queue<TreeNode*> que;
if(root==NULL)return 0;
que.push(root);
int k=0;
while(!que.empty()){
int size=que.size();
for(int i=size;i>0;i--){
TreeNode* tmp = que.front();
que.pop();
if(tmp->left!=NULL) que.push(tmp->left);
if(tmp->right!=NULL) que.push(tmp->right);
}
k++;
}
return k;
}
};
Leetcode111.二叉树的最小深度
/**
* 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 getdepth(TreeNode* root){
if(root==NULL)return 0;
if(root->right!=NULL&&root->left==NULL){
return 1+getdepth(root->right);
}
if(root->left!=NULL&&root->right==NULL){
return 1+getdepth(root->left);
}
int lef = getdepth(root->left);
int rig = getdepth(root->right);
return 1+min(lef,rig);
}
int minDepth(TreeNode* root) {
int result = getdepth(root);
return result;
}
};
LeetCode222.完全二叉树的节点个数
/**
* 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 getpoint(TreeNode* root){
if(root==NULL) return 0;
int lef = getpoint(root->left);
int rig = getpoint(root->right);
return 1+lef+rig;
}
int countNodes(TreeNode* root) {
int result = getpoint(root);
return result;
}
};