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;
    }
};

 

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