【学习点滴-数据结构-二叉树】二叉树转换为其镜像。
2012-05-31 15:45
585 查看
#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; }
相关文章推荐
- 【学习点滴-数据结构-二叉树】二叉查找树转换成双链表
- 【学习点滴-数据结构-二叉树】和为某一值的二叉树路径~
- 【学习点滴-数据结构-栈&队列】 栈的应用之一:数值转换
- 【学习点滴-数据结构-二叉树】求二叉树中某两个节点的最近公共祖先
- 【学习点滴-数据结构-二叉树】二叉查找树源码实现
- 【学习点滴-数据结构-二叉树】二叉树中找大于等于(min+max)/2的节点
- 【学习点滴-数据结构-二叉树】序列是否是二叉查找树的后序遍历结果
- 【学习点滴-数据结构-二叉树】判断二叉树是否是平衡二叉树
- 【学习点滴 -数据结构-二叉树】 二叉树的遍历(全)
- 【学习点滴-数据结构-二叉树】求二叉树两个节点之间的最大距离
- 【学习笔记----数据结构12-树、森林与二叉树的转换】
- 【学习点滴-数据结构-二叉树】整数序列放入二叉树中
- 数据结构学习--二叉树--二叉树遍历(1)
- 【剑指Offer学习】【面试题19 :二叉树的镜像】
- 数据结构学习之二叉树(实践篇)
- Interview----将一棵二叉树转换成其镜像
- 数据结构-----二叉树,树,森林之间的转换
- 【学习点滴-数据结构-栈&队列】 顺序栈的建立,入栈,出栈,判空
- 【学习点滴-数据结构-栈&队列】 颠倒一个栈。
- 【学习点滴-数据结构-栈&队列】 用两个栈模拟一个队列