c++ - 计算树中的所有节点

标签 c++ count binary-tree

这是我当前的代码。它工作正常,但我想不出一种方法将根节点添加到计数中,因为由于程序是递归的,它总是被添加很多次。

int countTree(tnode<T> *t)
{

int count = 0;


 if (t != NULL)
 {
     count = count + countTree(t->left);

if (t->left)
    { count++; }

  count = count + countTree(t->right);

if (t->right)
    { count++; }
}


return count;

};

最佳答案

二叉树中节点计数的通常递归是1 + count(left sub-tree) + count(right sub-tree),其中count(null) 返回 0。

所以它会是这样的:

int count(node *root)
{
    if (!root) { return 0; }

    return 1 + count(root->left) + count(root->right);
}

关于c++ - 计算树中的所有节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22030000/

相关文章:

c++ - 依赖倒置和普遍依赖

C++:可以在多个文件中调用静态变量吗?

postgresql - 我需要计算一个单词出现的不同行数

java - Java中如何向完全二叉树插入节点?

java - 我需要在java中找到一棵树的节点总数

java - 使用 BFT 的二叉树的最小深度?

c++ - 根据其他变量设置变量

c++ - 将处理器宏 __FUNCTION__ 与字符串连接起来

arrays - 如何计算 Delphi 中 JSON 数组中元素的数量

php - Mysql 函数 count() 逐行计数