leetcode 第 222 题:完全二叉树的节点个数(C++)

222. 完全二叉树的节点个数 - 力扣(LeetCode)
在这里插入图片描述
层次遍历:

class Solution {
public:
    int countNodes(TreeNode* root) {
        if(!root)   return 0;
        queue<TreeNode*> q;
        q.push(root);
        int res = 0, cnt = 1;
        while(!q.empty()){
            int size = q.size();
            if(size == cnt) res += cnt;
            else{
                res += size;    break;
            }
            cnt *= 2;
            for(int i = 0; i < size; ++i){
                auto cur = q.front();
                q.pop();
                if(cur->left)   q.push(cur->left);
                if(cur->right)  q.push(cur->right);
            }
        }
    	return res;
    }
};

递归:

class Solution {
public:
    int countNodes(TreeNode* root) {
        if(!root)   return 0;
        return countNodes(root->left) + countNodes(root->right) + 1;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_32523711/article/details/109102863
今日推荐