#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(): val(0), left(nullptr), right(nullptr) {}
TreeNode(int x): val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode* left, TreeNode* right): val(x), left(left), right(right) {}
};
/*
递归法:使用前序遍历计算完全二叉树的节点个数,时间复杂度O(n),空间复杂度O(logn)
*/
class Solution {
public:
// 1.确定函数入参及返回值
int getNodesNum(TreeNode* node) {
// 2.确定递归的终止条件
if(node == nullptr) return 0;
// 3.确定单层递归逻辑
int leftNum = getNodesNum(node->left);
int rightNum = getNodesNum(node->right);
int result = 1 + leftNum + rightNum;
return result;
}
int countNodes(TreeNode* root) {
return getNodesNum(root);
}
};
/*
迭代法:使用层序遍历计算完全二叉树的节点个数,时间/空间复杂度O(n)
*/
class Solution {
public:
int getNodesNum(TreeNode* root) {
queue<TreeNode*> que;
if(root != nullptr) que.push(root);
int result = 0;
while(!que.empty()) {
int size = que.size();
for(int i = 0; i < size; i++) {
TreeNode* cur = que.front();
que.pop();
result++;
if(cur->left) que.push(cur->left);
if(cur->right) que.push(cur->right);
}
}
return result;
}
};
|