二叉树(七)--完全二叉树的节点个数
这个对应力扣题目为:222. 完全二叉树的节点个数 - 力扣(LeetCode)
该题的大致思路如下:
这道题用两种方法来做,一是层序遍历,二是递归。
层序遍历就是在计算有多少节点进入队列就好了,这个思路还是很简单的。
递归也是记录每次走过的节点就好了,记住要+1(也就是节点本身)。
力扣题目答案如下:
层序遍历:
class Solution {
public:int countNodes(TreeNode* root) {queue<TreeNode*> que;int res = 0;if(root != nullptr){que.push(root);}while(!que.empty()){int size = que.size();for(int i = 0; i < size; i++){TreeNode* tmp = que.front();que.pop();if(tmp->left) que.push(tmp->left);if(tmp->right) que.push(tmp->right);res++;}}return res;}
};
递归:
class Solution {
public:int getnum(TreeNode* root){if(root == nullptr){return 0;}int left = getnum(root->left);int right = getnum(root->right);return left+right+1;}int countNodes(TreeNode* root) {int res = getnum(root);return res;}
};