#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <queue>
#include <iostream>
#include <malloc.h>
#define LEAF -1
using namespace std;
typedef struct BTreeNode{
BTreeNode* lchild;
BTreeNode* rchild;
int value;
}BTreeNode,*Btree;
BTreeNode* createTree(){
BTreeNode* T;
int t;
scanf("%d",&t);
if(t == LEAF){
T = NULL;
}else{
T = (BTreeNode *) malloc(sizeof(BTreeNode));
T->value = t;
T->lchild = createTree();
T->rchild = createTree();
}
return T;
}
//注意swap()函数。
void swap(BTreeNode ** left,BTreeNode** right){
BTreeNode * tmp = *left;
*left = *right;
*right = tmp;
}
void treeMirror(BTreeNode* &root){
if(root == NULL){
return ;
}
swap(&(root->lchild),(&root->rchild));
treeMirror(root->lchild);
treeMirror(root->rchild);
}
void preOrder(BTreeNode* root){
if(root != NULL){
printf("%d ",root->value);
}
if(root->lchild != NULL){
preOrder(root->lchild);
}
if(root->rchild !=NULL){
preOrder(root->rchild);
}
}
void mirrorNonRecursive(BTreeNode * &root){
if(root == NULL){
return ;
}
queue<BTreeNode*> que;
que.push(root);
while(!que.empty()){
BTreeNode *tmp = que.front();
que.pop();
swap(&(tmp->lchild),&(tmp->rchild));
if(tmp->lchild != NULL){
que.push(tmp->lchild);
}
if(tmp->rchild != NULL){
que.push(tmp->rchild);
}
}
}
main(){
BTreeNode * root;
root = createTree();
printf("Before Mirror : \n");
preOrder(root);
//treeMirror(root);
//printf("After Mirror : \n");
//preOrder(root);
printf("After MirrorNonRecur : \n");
mirrorNonRecursive(root);
preOrder(root);
system("pause");
return 0;
}
【学习点滴-数据结构-二叉树】二叉树转换为其镜像。
最新推荐文章于 2024-10-06 20:11:18 发布