222.完全二叉树的节点个数

在这里插入图片描述

思路:
先求二叉树的深度,然后根据深度求出二叉树最后一层空节点的个数,将满完全二叉树的节点个数减去空缺个数,就是待求节点数。


/**
 * 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;
 }
};
发布了90 篇原创文章 · 获赞 7 · 访问量 2168

猜你喜欢

转载自blog.csdn.net/weixin_43784305/article/details/103098027