/**
* 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 {
int maxnum=0;
void travesal(TreeNode* root,int depth){
if(root==nullptr){
return;}
depth++;
maxnum=max(maxnum,depth);
travesal(root->left,depth);
travesal(root->right,depth);
}
public:
int maxDepth(TreeNode* root) {
travesal(root,0);
return maxnum;
}
};
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 {
int mm=INT_MAX;
void dfs(TreeNode* root,int depth){
if(root==nullptr)return;
depth++;
if(root->left==nullptr&&root->right==nullptr){
mm=min(mm,depth);
}
dfs(root->left,depth);
dfs(root->right,depth);
}
public:
int minDepth(TreeNode* root) {
if(root==nullptr)return 0;
dfs(root,0);
return mm;
}
};
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==nullptr)return 0;
TreeNode* left=root->left;
TreeNode* right=root->right;
int ldepth=0,rdepth=0;
while(left){
left=left->left;
ldepth++;
}
while(right!=nullptr){
right=right->right;
rdepth++;
}
if(ldepth==rdepth){
return (2<<ldepth)-1;
}
return countNodes(root->left)+countNodes(root->right)+1;
}
};