赞
踩
要求:
1.采用二叉链表的方式进行存储
2.构造一个二叉树类
实现以下算法:
1.创建二叉树
2.对二叉树进行前序、中序、后序遍历
输入
扩展的前序序列.在一棵树处理结束后,根据响应判断是否处理下一棵树
输出
前序、中序、后序
样例输入
ab##c## Y abc#### N
样例输出
abc bac bca abc cba cba
- #include<iostream>
- #include<cstdio>
- #include<string>
- using namespace std;
- struct BiNode
- {
- char data;
- BiNode* rchild, * lchilld;
- };
-
- class BiTree
- {
- public:
- BiTree() { root = Creat(); }
- void Preorder() { preorder(root); }
- void Inorder() { inorder(root); }
- void Postorder() { postorder(root); }
- BiNode* getroot();
- private:
- BiNode* root;
- BiNode* Creat();
- void preorder(BiNode* bt);
- void inorder(BiNode* bt);
- void postorder(BiNode* bt);
- };
-
- BiNode* BiTree::getroot() { return root; }
- void BiTree::preorder(BiNode* bt)
- {
- if (bt == nullptr) return;
- else {
- cout << bt->data;
- preorder(bt->lchilld);
- preorder(bt->rchild);
- }
- }
-
- void BiTree::inorder(BiNode* bt)
- {
- if (bt == nullptr) return;
- else {
- inorder(bt->lchilld);
- cout << bt->data;
- inorder(bt->rchild);
- }
- }
-
- void BiTree::postorder(BiNode* bt) {
- if (bt == nullptr) return;
- else {
- postorder(bt->lchilld);
- postorder(bt->rchild);
- cout << bt->data;
- }
- }
-
- BiNode* BiTree::Creat()
- {
- BiNode* bt = nullptr;
- char ch; cin >> ch;
- if (ch == '#') bt = nullptr;
- else {
- bt = new BiNode;
- bt->data = ch;
- bt->lchilld = Creat();
- bt->rchild = Creat();
- }
- return bt;
- }
-
-
- int main()
- {
- char a = 'Y';
- while (a == 'Y') {
- BiTree T;
- T.Preorder();
- cout << endl;
- T.Inorder();
- cout << endl;
- T.Postorder();
- cout << endl;
- cin >> a;
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。