根据数组创建二叉树,左右子树交换,层序遍历,中序遍历

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<map>
#include<vector>
#include<set>
#include<queue>
#include<sstream>
using namespace std;
const double Pi=acos(-1.0);
struct node
{
    string data;
    node * lchild;
    node * rchild;
};
//根据数组创建二叉树
node * create(string str1[],int len,int pos){

if(pos>=len)
    return NULL;
node * root=new node;
root->data=str1[pos];
root->lchild=create(str1,len,2*pos+1);
root->rchild=create(str1,len,2*pos+2);
return root;
}
//左右子树交换
void  change(node * &root){

if(root==NULL)
    return;

change(root->lchild);
change(root->rchild);

node * temp=new node;
temp=root->lchild;
root->lchild=root->rchild;
root->rchild=temp;

}
//层序遍历
void LayerOrder(node * root){
queue<node *> q;
q.push(root);
while(!q.empty()){
    node * now=q.front();
    cout<<now->data<<",";
    q.pop();
    if(now->lchild!=NULL)
    q.push(now->lchild);
    if(now->rchild!=NULL)
    q.push(now->rchild);
}

}
//中序遍历
int sum=7;
void inOrder(node * root){
if(root==NULL)
    return ;
inOrder(root->lchild);
cout<<root->data;
if(sum--)
    cout<<",";
inOrder(root->rchild);
}

int main()
{
    int D;
    cin>>D;
    getchar();
    string str;
   getline(cin,str);
    string str1[35];
    for(int i=0;i<str.length();i++){
        if(str[i]==',')
            str[i]=' ';
    }
    stringstream ss;
    ss.str(str);
    for(int i=0;i<D;i++){
        ss>>str1[i];
    }

    node * root=create(str1,D,0);
    change(root);
    inOrder(root);






    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值