交换二叉树每个结点的左孩子和右孩子
#define _CRT_SECURE_NO_WARNINGS#include <iostream>
using namespace std;typedef char ElemType;
#define ERROR 0
#define OK 1
#define STR_SIZE 1024
typedef struct BiTNode
{ElemType data;BiTNode* lchild, * rchild;
}BiTNode, * BiTree;void draw(BiTNode* root);bool Create_tree(BiTree& T)
{ElemType x = 0;cin >> x;if (x == '#'){T = NULL;}else{T = (BiTree)malloc(sizeof(BiTNode));if (T == NULL){cout << "内存无法分配!!!" << endl;return ERROR;}T->data = x;T->lchild = NULL;T->rchild = NULL;Create_tree(T->lchild);Create_tree(T->rchild);}return OK;
}void PreOrder(BiTree T)
{if (T != NULL){cout << T->data;PreOrder(T->lchild);PreOrder(T->rchild);}
}void InOrder(BiTree T)
{if (T != NULL){InOrder(T->lchild);cout << T->data;InOrder(T->rchild);}
}void PostOrder(BiTree T)
{if (T != NULL){PostOrder(T->lchild);PostOrder(T->rchild);cout << T->data;}
}
//---------------------------------核心代码---------------------------------//
bool exchange(BiTree& T)
{if (T == NULL){return ERROR;}if (T->lchild == NULL && T->rchild == NULL){return OK;}else{BiTNode* temp = NULL;temp = T->lchild;T->lchild = T->rchild;T->rchild = temp;}exchange(T->lchild);exchange(T->rchild);return OK;
}
//---------------------------------核心代码---------------------------------//
//交换二叉树每个结点的左孩子和右孩子
//测试1:123##4##5##
//测试2:12##3##
//测试3:123###4##
int main(void)
{cout << "//------生成一颗树---------//" << endl;BiTree T = NULL;Create_tree(T);PreOrder(T);cout << endl;InOrder(T);cout << endl;PostOrder(T);cout << endl;cout << "//------生成一颗树---------//" << endl;cout << "//------原始树图形---------//" << endl;draw(T);exchange(T);cout << "//------修改树图形---------//" << endl;draw(T);return 0;
}//参考博客:https://blog.csdn.net/weixin_42109012/article/details/92250160
/*****************************************************************************
* @date 2020/4/19
* @brief 水平画树
* @param node 二叉树节点
* @param left 判断左右
* @param str 可变字符串
*****************************************************************************/
void draw_level(BiTNode* node, bool left, char* str) {if (node->rchild) {draw_level(node->rchild, false, strcat(str, (left ? "| " : " ")));}printf("%s", str);printf("%c", (left ? '\\' : '/'));printf("-----");printf("%c\n", node->data);if (node->lchild) {draw_level(node->lchild, true, strcat(str, (left ? " " : "| ")));}// " " : "| " 长度为 6str[strlen(str) - 6] = '\0';
}/*****************************************************************************
* @date 2020/4/19
* @brief 根节点画树
* @param root 二叉树根节点
*****************************************************************************/
void draw(BiTNode* root) {char str[STR_SIZE];memset(str, '\0', STR_SIZE);/*** 1. 在 windows 下,下面是可执行的* 2. 在 Linux 下,执行会报 Segmentation fault* 需要使用中间变量*/if (root->rchild) {draw_level(root->rchild, false, str);}printf("%c\n", root->data);if (root->lchild) {draw_level(root->lchild, true, str);}
}
测试1
测试2
测试3