qq_39677327
2022-05-20 17:20
采纳率: 94.6%
浏览 38

代码完善数据结构二叉树

建立一棵二叉树,树的形态自定,完成以下操作:
(1)输出该二叉树的前序遍历序列;
(2)输出该二叉树的中序遍历序列;
(3)输出该二叉树的后序遍历序列。

代码完善

#include<iostream>
using namespace std;

struct BTree
{
    char data;
    BTree *lchild, *rchild;
};

class Tree
{
public:
    Tree() { root = Create(root); }
    ~Tree() { relase(root); }
    void preorder() { preorder(root); }
    void inorder() { inorder(root); }
    void postorder() { postorder(root); }
private:
    BTree *root;
    BTree *Create(BTree *t);
    void relase(BTree *t) ;
    void preorder(BTree *t);
    void inorder(BTree *t);
    void postorder(BTree *t);
};

BTree *Tree::Create(BTree *t)
{
    char ch;
    cin >> ch;//输入结点
    if (ch == '#')
    {
        t = NULL;
    }
    else
    {
        t = new BTree;
        t->data = ch;
        t->lchild = Create(t->lchild);
        t->rchild = Create(t->rchild);
    }
    return t;
}

void Tree::preorder(BTree *t)
{
    if (t == NULL)
    {
        return;
    }
    else
    {
        cout << t->data;
        preorder(t->lchild);
        preorder(t->rchild);
    }
}

int main()
{
    cout << "请输入二叉树的结点数据:";
    Tree A;
    cout << "前序遍历为:" << endl;
    A.preorder();
    cout << "中序遍历为:" << endl;
    A.inorder();
    cout << "后序遍历为:" << endl;
    A.postorder();
    return 0;
}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题