创作目的:为了方便自己后续复习重点,以及养成写博客的习惯。
一、二叉树的最大深度
思路:按ledcode题解所有使用深度优先算法
ledcode题目:https://leetcode.cn/problems/maximum-depth-of-binary-tree/description/
AC代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode* root) {
if(root == NULL){
return 0;
}
return fmax(maxDepth(root->left),maxDepth(root->right)) + 1;
}
二、二叉树的最小深度
lecode题目:
https://leetcode.cn/problems/minimum-depth-of-binary-tree/description/
AC代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int minDepth(struct TreeNode* root) {
if(root == NULL){
return 0;
}
if(root->left == NULL && root->right == NULL){
return 1;
}
int min_depth = INT_MAX;
if(root->left != NULL){
min_depth = fmin(minDepth(root->left),min_depth);
}
if(root->right != NULL){
min_depth = fmin(minDepth(root->right),min_depth);
}
return min_depth + 1;
}
三、完全二叉树的节点个数
思路:依据于普通二叉树的逻辑
ledcode题目:https://leetcode.cn/problems/count-complete-tree-nodes/description/
AC代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool exists(struct TreeNode* root,int level,int k){
int bits = 1 << (level - 1);
struct TreeNode* node = root;
while(node != NULL && bits > 0){
if(!(bits & k)){
node = node->left;
}else{
node = node ->right;
}
bits >>=1;
}
return node != NULL;
}
int countNodes(struct TreeNode* root) {
if(root == NULL){
return 0;
}
int level = 0;
struct TreeNode* node = root;
while(node->left != NULL){
level++;
node = node->left;
}
int low = 1 << level,high = (1 <<(level + 1)) - 1;
while(low < high){
int mid = (high - low) / 2 + low;
if(exists(root,level,mid)){
low = mid;
}else{
high = mid - 1;
}
}
return low;
}
全篇后记:
完全二叉树的节点个数c代码参考ledcode官方题解,最后AC的结果是超时,自己目前并没有很好的解决思路,鉴于一刷要求不高,留到以后再解决吧。