【刷题日记】二叉树-完全二叉树的节点个数-L222-Easy
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
学习点
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Solution { public: int countNodes(TreeNode* root) { queue<TreeNode*> qe; if (root) qe.push(root); int node_cnt = 0; while (!qe.empty()) { int node_num = qe.size(); for (int i = 0; i < node_num; ++i) { TreeNode *tmp = qe.front(); qe.pop(); ++node_cnt; if (tmp->left) qe.push(tmp->left); if (tmp->right) qe.push(tmp->right); } }
return node_cnt; } };
|