(3+2)专科段数据结构专项练习86-89

7-86 中序遍历二叉树

按完全二叉树的层次遍历给出一棵二叉树的遍历序列(其中用0表示虚结点),要求输出该二叉树的深度及中序遍历该二叉树得到的序列。

输入格式:

首先输入一个整数T,表示测试数据的组数,然后是T组测试数据。每组测试数据首先输入一个正整数n(n≤1000),代表给出的二叉树的结点总数(当然,其中可能包含虚结点)。结点编号均为正整数,且各不相同。
然后输入n个正整数,表示按完全二叉树(即第1层1个结点,第2层2个,第3层4个,第4层有8个……)的层次遍历给出的二叉树遍历序列,如果某个结点不存在(虚结点),则以0代替。

输出格式:

对于每组测试,第一行输出中序遍历二叉树得到的序列(每两个数据之间留一个空格),第二行输出二叉树的深度。

输入样例:

4
1 1
4 1 4 0 2
11 4 2 0 1 5 0 0 0 0 7 6
3 1 0 0

 输出样例:

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

代码 

#include<bits/stdc++.h>
using namespace std;
template<class T>
struct treeNode{
    T data;
    treeNode *L_child,*R_child;
};
int nodeData[1005];//存储输入到数字数组
int n;
int l; //用来判断是否是第一次输出 
template<class T>//模板类
class Tree
{
    public:
        Tree(){
            initTree();
        };
        void initTree();
        treeNode<T>* createNode(int nodeNum);
        void LNR(treeNode<T> *root);
        int getDep(treeNode<T> *root);
        treeNode<T>* getRoot(){
         return this->root; 
  };
    private:
        treeNode<T> *root;
        
};

template<class T>
void Tree<T>::initTree()//初始化根节点
{
    this->root = new treeNode<T>();
    root->L_child=root->R_child=NULL;
}

template<class T>
treeNode<T>* Tree<T>::createNode(int nodeNum)//创建节点
{
 if(nodeNum>n) return NULL; //如果结点编号超过了总数n,返回NULL 
 if(nodeData[nodeNum]==0) return NULL; //如果该结点的数是0,为空结点,返回NULL 
 treeNode<T> *node = new treeNode<T>();
 node->data=nodeData[nodeNum];
 node->L_child=createNode(nodeNum*2);
 node->R_child=createNode(nodeNum*2+1);
 return node; 
}

template<class T>
void Tree<T>::LNR(treeNode<T> *root){
 if(root==NULL) return;
 LNR(root->L_child);
 if(l==0){
   //这里判断是不是第一次输出 ,pta上要判断空格,所以要注意 
  cout<<root->data;
  l=1; 
 }
 else
  cout<<" "<<root->data;
 LNR(root->R_child); 
}

template<class T>
int Tree<T>::getDep(treeNode<T> *root)
{
 if(root==NULL) return 0;
 int depL = getDep(root->L_child);
 int depR = getDep(root->R_child);
 int max = depL>depR?depL+1:depR+1;
 return max;
}

void initNum()
{
    for(int i=0;i<=1002;i++){
        nodeData[i]=0;
    }
    
}
int main()
{
    int t;
    cin>>t;
    while(t--){
        initNum();
        cin>>n;
        l=0; 
        for(int
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值