递归建立树,递归求树的节点数
递归式子是左子树节点数+右子树节点数+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;
}