编写求一棵二叉树中结点总数的算法。
void count(BiTree T){
int n=0;
if(T!=NULL){
count(T->lchild);
count(T->rchild);
n++;
}
return n;
int GetNodesNum(BTNode * root)
{
if(root==NULL) return 0;
if(root->lchild) return GetNodesNum(root->lchild)+1;
if(root->rchild) return GetNodesNum(root->rchild)+1;
return 1;
int func(BT root)
{if(root==NULL) return 0;
int sum=1;
return sum+func(BT->lchild)+func(BT->rchild);
#include <iostream> // 二叉树节点结构 struct TreeNode { int data; TreeNode* left; TreeNode* right; TreeNode(int val) : data(val), left(nullptr), right(nullptr) {} }; // 计算二叉树节点总数的递归函数 int countNodes(TreeNode* root) { if (root == nullptr) { return 0; // 如果树为空,返回0 } // 递归计算左子树和右子树的节点总数,然后加上根节点(1) int leftCount = countNodes(root->left); int rightCount = countNodes(root->right); return leftCount + rightCount + 1; }
void count_preorder(Bitree *t, int *n){
if(t!=NULL){
*n++;
count_preorder(t->lchild);
int getSize(Tree* t){
if(t==NULL){
return 0;
int sum=0;
TreeNode* p=t;
if(p!=NULL){
sum=sum+getSize(p->lchild);
sum=sum+1;
sum=sum+getSize(p-rchild);
return sum;
void count_preorder(Bitree *t, int *n)
if(t!=NULL)
{*n++;
count_preorder(t->lchild); }
int nodenum(Bitree t){ if(t) return 1+nodenum(t->lchild)+nodenum(t->rchild); else return 0; }
int count(BTree *p)
if(p!=NULL)
sum++;
count(p->lchild);
count(p->rchild);
int sumpoint(BTNode *p) { int n = 0; if (p != NULL) { n++; sumpoint(p->lchild); sumpoint(p->rchild); } return n; }
答案: (以先序遍历的方...
用户登录可进行刷题及查看答案
答案: (以先序遍历的方法为例)
登录后提交答案