递归建立树,递归求树的节点数
递归式子是左子树节点数+右子树节点数+1
#include<iostream>
#include<stack>
using namespace std;
int count=0;
struct Node{
char data;
Node *lchild;
Node *rchild;
};
Node*createTree(){
char x;
cin>>x;
if(x=='#')return NULL;
Node *root=new Node;
root->data=x;
root->lchild=createTree();
root->rchild=createTree();
return root;
}
int NumOfNode(Node* root){
if(root){
count++;
return NumOfNode(root->lchild)+NumOfNode(root->rchild)+1;
}
return 0;
}
int main(){
Node *root=createTree();
int n=NumOfNode(root);
cout<<"这棵树一共有"<<n<<"个节点。" <<endl;
return 0;
}

这篇博客介绍了如何使用递归创建二叉树,并计算树的节点数。通过输入字符流构建二叉树,然后利用递归函数计算树的节点总数。递归公式为:左子树节点数 + 右子树节点数 + 1。程序在main函数中读取并展示树的节点数量。

被折叠的 条评论
为什么被折叠?



