由顺序方式存储的完全二叉树进行重建(c++)

题目描述

按顺序方式存储的一棵完全二叉树的结点记录,结点个数为n。根据所输入的顺序结构的结点记录建立二叉树,输出树的先序,中序和后序遍历结果。
注:数字“0”表示不存在此结点,没有孩子结点。

输入

树结点个数n
顺序方式存储的完全二叉树

输出

先序遍历输出
中序遍历输出
后序遍历输出

样例输入

10
1 2 0 3 4 0 0 5 6 7

样例输出

1 2 3 5 6 4 7
5 3 6 2 7 4 1
5 6 3 7 4 2 1

提示

数字“0”的孩子结点全部为“0”

这是非常典型的树的遍历,运用的是递归的思想
(关于树的一些基础知识,大家应该右一定的了解)
先序:根左右
中序:左根右
后序:左右根

我们可以理解为这三种方式的遍历根根节点的遍历顺序有关
(大家应该明白三种遍历方式的流程,这里就不讲解了)

#include <iostream>

using namespace std;

class Tree {
public:
    int* data;
    int lchild = 0;//左孩子
    int rchild = 0;//右孩子
    int maxSize;
    Tree() {}
    Tree(int* elem, int n) {
        maxSize = n;
        data = new int[maxSize];
        for (int i = 0; i < n; i++)
            data[i] = elem[i];
    }
    ~Tree() {
        delete []data;
    }

    void PreOrder(int root = 0) {//前序遍历,三种遍历方式其实就是根节点的顺序不同
        if(data[root]!=0)//根节点
            cout << data[root] << " ";
        
        lchild = root * 2 + 1;//左孩子
        if (lchild < maxSize)
            PreOrder(lchild);

        rchild = root * 2 + 2;//右孩子
        if (rchild < maxSize)
            PreOrder(rchild);
    }
    void MedOrder(int root = 0) {//中序遍历
        lchild = root * 2 + 1;//左孩子
        if (lchild < maxSize)
            MedOrder(lchild);

        if (data[root] != 0)//根节点
            cout << data[root] << " ";

        rchild = root * 2 + 2;//右孩子
        if (rchild < maxSize)
            MedOrder(rchild);
    }
    void PosOrder(int root = 0) {//后序遍历
        lchild = root * 2 + 1;
        if (lchild< maxSize)//左孩子
            PosOrder(lchild);

        rchild = root * 2 + 2;
        if (rchild < maxSize)//右孩子
            PosOrder(rchild);

        if (data[root] != 0)//根节点
            cout << data[root] << " ";
    }
};


int main() {
    int n;
    cin >> n;
    int* arr = new int[n];
    for (int i = 0; i < n; i++)
        cin >> arr[i];

    Tree tree(arr, n);
    tree.PreOrder();
    cout << endl;
    tree.MedOrder();
    cout << endl;
    tree.PosOrder();
    cout << endl;

    return 0;
}

有问题,欢迎交流

  • 5
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值