首页 > 其他分享 >代码随想录:完全二叉树的节点个数

代码随想录:完全二叉树的节点个数

时间:2025-01-12 20:45:55浏览次数:1  
标签:node right TreeNode int nullptr 随想录 二叉树 节点 left

拿到一个节点,先判断是不是等边三角形,若是直接返回2^n-1,位运算写在专题中

/**
 * 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* node) {
        if (node == NULL) {
            return 0;
        }
        TreeNode* l = node->left;
        TreeNode* r = node->right;
        int left = 1;
        int right = 1;
        while (l) {
            l = l->left;
            left++;
        }
        while (r) {
            r = r->right;
            right++;
        }
        if (left == right) {
            return fang(left) - 1;
        } else {
            return countNodes(node->left) + countNodes(node->right) + 1;
        }
    }

    int fang(int a){
        int res=1;
        for(int i=0;i<a;i++){
            res*=2;
        }
        return res;
    }
};

标签:node,right,TreeNode,int,nullptr,随想录,二叉树,节点,left
From: https://www.cnblogs.com/huigugu/p/18667248

相关文章