SWUST OJ#1105 交换二叉树的孩结点

目录

题目

思路

代码


题目

题目描述

编程程序实现将二叉树中所有结点的左右孩子互换

输入

二叉树的先序序列(输入先序序列建立二叉树)。

输出

第一行为交换后的二叉树的中序序列

第二行为交换后的二叉树的先序序列

样例输入

ABD###C###

样例输出

CABD
ACBD

 

思路

翻转二叉树可以先镜面先序遍历(根->右孩子->左孩子),并储存。然后再依次先序创建之前储存的镜面先序遍历

//创建翻转的二叉树
char node[10005];
int sum2=0;
void create(BinaryTree* &root) {
    BTNode *q;
    q=new BTNode;
    q->data=node[sum2++];
    if(q->data=='#') {
        root=q=NULL;
        return;
    }
    root=q;
    create(root->left);
    create(root->right);
}
//镜面先序遍历
int sum1=0;
void sy_BTProOrder(BinaryTree* &root) {
    if(root==NULL) {
        node[sum1++]='#';
        return;
    }
    node[sum1++]=root->data;
    sy_BTProOrder(root->right);
    sy_BTProOrder(root->left); 
}

代码

二叉树模板,二叉树介绍

#include <bits/stdc++.h>
using namespace std;
//定义
typedef struct BTNode {
    char data;
    BTNode *left;
    BTNode *right;
}BinaryTree;
void Create(BinaryTree* &root) {
    BTNode *q;
    q=new BTNode;
    cin>>q->data;
    if(q->data=='#') {
        root=q=NULL;
        return;
    }
    root=q;
    Create(root->left);
    Create(root->right);
}
//创建二叉树
char node[10005];
int sum2=0;
void create(BinaryTree* &root) {
    BTNode *q;
    q=new BTNode;
    q->data=node[sum2++];
    if(q->data=='#') {
        root=q=NULL;
        return;
    }
    root=q;
    create(root->left);
    create(root->right);
}
//镜面先序遍历
int sum=0;
void sy_BTProOrder(BinaryTree* &root) {
    if(root==NULL) {
        node[sum++]='#';
        return;
    }
    node[sum++]=root->data;
    sy_BTProOrder(root->right);
    sy_BTProOrder(root->left); 
}
//前序遍历
void BTProOrder(BinaryTree* &root) {
    if(root==NULL) return;
    cout<<root->data;
    BTProOrder(root->left);
    BTProOrder(root->right);
}
//中序遍历
void BTInOrder(BinaryTree* &root) {
    if(root==NULL) return;
    BTInOrder(root->left);
    cout<<root->data;
    BTInOrder(root->right);
}
int main() {
    BinaryTree *root1,*root2;
    Create(root1);
    sy_BTProOrder(root1);
    create(root2);
    BTInOrder(root2);
    cout<<endl;
    BTProOrder(root2);
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

青衿白首志

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值