代码随想录第十四天(一刷&&C语言)|二叉树的最大深度&&二叉树的最小深度&&完全二叉树的节点个数

创作目的:为了方便自己后续复习重点,以及养成写博客的习惯。

一、二叉树的最大深度

思路:按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的结果是超时,自己目前并没有很好的解决思路,鉴于一刷要求不高,留到以后再解决吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值