#include<iostream>using namespace std;struct BiNode{char data;BiNode *lchild,*rchild;};class BiTree{public:BiTree(BiNode *root) //有參構造函數,初始化一顆二叉樹。{this->root=Creat();}BiNode *getroot(){return root;}~BiTree() //析構函數,釋放二叉樹{Release(root);}void PreOrder(BiNode *root); //前序遍歷void InOrder(BiNode *root); //中序遍歷void PostOrder(BiNode *root); //后序遍歷 private:BiNode *root;BiNode *Creat() //有參函數調用{char ch;cin>>ch;BiNode *root;if(ch=='#') root=NULL;else{root=new BiNode;root->data=ch;root->lchild=Creat();root->rchild=Creat();}return root;}void Release(BiNode *root) //析構函數調用 {if(root!=NULL){Release(root->lchild);Release(root->rchild);delete root;}}};void BiTree::PreOrder(BiNode *root) //qian{if(root==NULL) return;else{cout<<root->data;PreOrder(root->lchild);PreOrder(root->rchild);}}void BiTree::InOrder(BiNode *root) //zhong{if(root==NULL) return;else{InOrder(root->lchild);cout<<root->data;InOrder(root->rchild);}}void BiTree::PostOrder(BiNode *root) //hou{if(root==NULL) return;else{PostOrder(root->lchild);PostOrder(root->rchild);cout<<root->data;}}二叉樹建立并遍歷。 主函數代碼改怎么寫? int main(){.............}
3 回答

暮色呼如
TA貢獻1853條經驗 獲得超9個贊
1.這個你要仔細看下Create()函數啊,根據這個函數的功能;
2.這些代碼其實都不需要參數啊,因為這是個類啊,最好再熟悉下類和成員的基礎概念,比如:
BiTree()
{
this->root=Creat();
}
就可以了,因為root是類的私有數據成員,不需要出現在參數里面了。
最簡單的主函數如下:
int main(){
BiTree theTree();
theTree.PreOrder();
theTree.Release();
return 0;
}

哈士奇WWW
TA貢獻1799條經驗 獲得超6個贊
int main(){
BiNode* root;
BiTree* tree = new BiTree(root);
tree->preOrder(root);
tree->inOrder(root);
tree->postOrder(root);
delete tree;
}

LEATH
TA貢獻1936條經驗 獲得超7個贊
如下主函數調用實現:
int main()
{
/*
BiTree theTree();
theTree.PreOrder();
theTree.Release();
*/
BiNode * root = new BiNode;
BiTree hao(root);
hao.PreOrder(root);
hao.InOrder(root);
hao.PostOrder(root);
return 0;
}
- 3 回答
- 0 關注
- 447 瀏覽
添加回答
舉報
0/150
提交
取消