思路:
先求二叉树的深度,然后根据深度求出二叉树最后一层空节点的个数,将满完全二叉树的节点个数减去空缺个数,就是待求节点数。
/**
* 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) return 0;
int n = countDepth(root);
int sum = pow(2, n) - 1;
mycountNodes(root, sum, 1, n);
return sum;
}
int countDepth(TreeNode* root)
{
if (!root) return 0;
int n = 0;
while (root)
{
root = root->left;
++n;
}
return n;
}
void mycountNodes(TreeNode* root, int& sum, int depth, int n)
{
if (!root) return;
if (depth == n - 1)
{
if (!root->right) --sum;
if (!root->left) --sum;
}
mycountNodes(root->left, sum, depth + 1, n);
mycountNodes(root->right, sum, depth + 1, n);
}
};
时间复杂度和空间复杂度好像和普通的递归求节点个数的算法差不多
普通的递归算法
/**
* 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 == NULL) return 0;
return countNodes(root->left) + countNodes(root->right) + 1;
}
};