当前位置:   article > 正文

交换二叉树的左右子树——非递归方式_非递归实现二叉树左右子树交换

非递归实现二叉树左右子树交换
这是华为的一道机试题,其实并不难,不让用递归可以用栈来解决,具体的代码如下:
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct node{
  4. char data ;
  5. struct node* left ;
  6. struct node* right ;
  7. };
  8. struct tree{
  9. struct node* root ;
  10. };
  11. void tree_create( struct node** node){
  12. char data;
  13. scanf("%c" , &data);
  14. if(data == '#' ){
  15. *node = NULL;
  16. }
  17. else{
  18. *node = ( struct node*)malloc(sizeof( struct node));
  19. (*node)-> data = data;
  20. tree_create(&(*node)-> left);
  21. tree_create(&(*node)-> right);
  22. }
  23. }
  24. void tree_destory( struct node** node){
  25. if(*node != NULL){
  26. tree_destory(&(*node)-> left);
  27. tree_destory(&(*node)-> right);
  28. free(node);
  29. }
  30. }
  31. void tree_first( struct node* node){
  32. if(node == NULL)
  33. return;
  34. printf("%c " , node->data);
  35. tree_first(node-> left);
  36. tree_first(node-> right);
  37. }
  38. static struct node* stack[5] = {0};
  39. static int pos = -1;
  40. void push( struct node* node){
  41. stack[++pos] = node;
  42. }
  43. void pop(){
  44. --pos;
  45. }
  46. int empty(){
  47. return pos == -1;
  48. }
  49. struct node* top(){
  50. return stack[pos];
  51. }
  52. void exchange( struct node* node){
  53. struct node* tnode = node;
  54. struct node* tmp = NULL;
  55. if(node == NULL)
  56. return;
  57. while(1){
  58. tmp = tnode-> left;
  59. tnode-> left = tnode->right ;
  60. tnode-> right = tmp;
  61. if(tnode->right ){
  62. push(tnode-> right);
  63. }
  64. if(tnode->left ){
  65. tnode = tnode->left;
  66. }
  67. else{
  68. if(!empty()){
  69. tnode = top();
  70. pop();
  71. }
  72. else{
  73. break;
  74. }
  75. }
  76. }
  77. }
  78. int main(){
  79. struct tree tree;
  80. tree_create(&tree. root);
  81. printf("交换前的先序遍历:" );
  82. tree_first(tree. root);
  83. printf("\n" );
  84. exchange(tree. root);
  85. printf("交换后的先序遍历:" );
  86. tree_first(tree. root);
  87. printf("\n" );
  88. tree_destory(&tree. root);
  89. return 0;
  90. }


本文链接:http://blog.csdn.net/girlkoo/article/details/17605349

本文作者:girlkoo

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/737649
推荐阅读
相关标签
  

闽ICP备14008679号