c++遞迴建立樹,遞迴求樹的節點數
阿新 • • 發佈:2021-01-17
技術標籤:資料結構基礎演算法
遞迴建立樹,遞迴求樹的節點數
遞迴式子是左子樹節點數+右子樹節點數+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;
}