交换二叉树的左右子树——非递归方式
来源:互联网 发布:小鱼儿主页最近域名 编辑:程序博客网 时间:2024/06/14 01:02
这是华为的一道机试题,其实并不难,不让用递归可以用栈来解决,具体的代码如下:
#include <stdio.h>#include <stdlib.h>struct node{ char data ; struct node* left ; struct node* right ;};struct tree{ struct node* root ;};void tree_create( struct node** node){ char data; scanf("%c" , &data); if(data == '#' ){ *node = NULL; } else{ *node = ( struct node*)malloc(sizeof( struct node)); (*node)-> data = data; tree_create(&(*node)-> left); tree_create(&(*node)-> right); }}void tree_destory( struct node** node){ if(*node != NULL){ tree_destory(&(*node)-> left); tree_destory(&(*node)-> right); free(node); }}void tree_first( struct node* node){ if(node == NULL) return; printf("%c " , node->data); tree_first(node-> left); tree_first(node-> right);}static struct node* stack[5] = {0};static int pos = -1;void push( struct node* node){ stack[++pos] = node;}void pop(){ --pos;}int empty(){ return pos == -1;}struct node* top(){ return stack[pos];}void exchange( struct node* node){ struct node* tnode = node; struct node* tmp = NULL; if(node == NULL) return; while(1){ tmp = tnode-> left; tnode-> left = tnode->right ; tnode-> right = tmp; if(tnode->right ){ push(tnode-> right); } if(tnode->left ){ tnode = tnode->left; } else{ if(!empty()){ tnode = top(); pop(); } else{ break; } } }}int main(){ struct tree tree; tree_create(&tree. root); printf("交换前的先序遍历:" ); tree_first(tree. root); printf("\n" ); exchange(tree. root); printf("交换后的先序遍历:" ); tree_first(tree. root); printf("\n" ); tree_destory(&tree. root); return 0;}
本文链接:http://blog.csdn.net/girlkoo/article/details/17605349
本文作者:girlkoo
1 0
- 交换二叉树的左右子树——非递归方式
- 二叉树中所有节点的左右子树相互交换 递归与非递归程序
- 二叉树中所有节点的左右子树相互交换 递归与非递归程序
- [Java]将二叉树的左右子树交换 非递归实现
- 二叉树左右子树交换的算法
- 二叉树左右子树的交换
- 二叉树交换左右子树
- 经典算法学习——交换二叉树的左右子树(二叉树的翻转)
- 非递归实现交换二叉树的左右子节点
- 反转二叉树,即交换所有结点的左右子树,但不能使用递归方法。
- 6_43_递归交换二叉树中所有节点的左右子树
- java实现二叉树的子树交换的递归与非递归写法
- 非递归交换二叉树左右子树:BinaryTree:Exchange the left child and the right child without recursive method
- 1021_二叉树的复制和左右子树交换
- 交换左右子树(二叉树)
- 学习笔记—交换二叉树所有节点中的左右子树
- C语言二叉树建立,遍历(递归与非递归),交换子树
- 二叉树(三)二叉树的高度、交换两个子树左右节点
- About code review
- 2013-12-26一次library cache lock的诊断--OEM引发的
- HTML5的新功能
- ondraw() 和dispatchdraw()的区别
- fflush和fsync的一些总结
- 交换二叉树的左右子树——非递归方式
- 测试
- cocos2d-x-lua工程的lua脚本加密
- mongodb最大连接数、最大连接数修改
- HTML5全局属性
- document对象
- 不使用UIImagePickerController实现读取相册图片的方法
- Android开发性能优化简介
- C语言各种数据类型及其在系统中占的字节和取值范围