leetcode 222. Count Complete Tree Nodes 统计完全二叉树节点个数

https://leetcode.com/problems/count-complete-tree-nodes/

层次遍历二叉树,将节点压入队列,取出队列头部,将其左右子树压入队列。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int countNodes(TreeNode* root) {
        if(root==nullptr)
            return 0;
        if(root->left==nullptr && root->right==nullptr)
            return 1;
        queue<TreeNode*> q;
        q.push(root);
        int n = 0;
        while(!q.empty()){
            n+=1;
            TreeNode* tmp = q.front();
            q.pop();
            if(tmp->left!=nullptr)
                q.push(tmp->left);
            if(tmp->right!=nullptr)
                q.push(tmp->right);
        }
        return n;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章