#includeiostreamusing namespace std;typedef struct BiNode char data; struct BiNode lchildrchild;BiTNodeBiTree;void CreateBiTreeBiTree &T char ch; cin ch; ifch==# T
The given code has several issues:
- In the
NodeCountfunction, the base case is checking if the tree is NULL, but the function returns 0 instead of 1. This is incorrect as a single node tree should have a count of 1. The correct statement should beif(T==NULL) return 1; - The function is returning
T->lchild+T->rchildwhich is not a valid operation asT->lchildandT->rchildare pointers to nodes, not integers. The correct statement should bereturn NodeCount(T->lchild) + NodeCount(T->rchild); - The main function is using
printfinstead ofcoutto print the result. This is not an issue, but it is not consistent with the rest of the code which usescinandcout.
Here is the corrected code:
#include<iostream>
using namespace std;
typedef struct BiNode{
char data;
struct BiNode *lchild,*rchild;
}BiTNode,*BiTree;
void CreateBiTree(BiTree &T){
char ch;
cin >> ch;
if(ch=='#') T=NULL;
else{
T=new BiTNode;
T->data=ch;
CreateBiTree(T->lchild);
CreateBiTree(T->rchild);
}
}
int NodeCount ( BiTree T)
{
if(T==NULL) return 1;
if(T->lchild==NULL&&T->rchild!=NULL)
return 1;
if(T->lchild!=NULL&&T->rchild==NULL)
return 1;
return NodeCount(T->lchild) + NodeCount(T->rchild);
}
int main(){
BiTree T;
CreateBiTree(T);
cout << NodeCount(T);
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/fkhU 著作权归作者所有。请勿转载和采集!