当前位置:   article > 正文

25、数据结构/二叉树相关练习20240207

25、数据结构/二叉树相关练习20240207

一、二叉树相关练习

请编程实现二叉树的操作

1.二叉树的创建

2.二叉树的先序遍历

3.二叉树的中序遍历

4.二叉树的后序遍历

5.二叉树各个节点度的个数

6.二叉树的深度

代码:

  1. #include<stdlib.h>
  2. #include<string.h>
  3. #include<stdio.h>
  4. typedef struct node//定义二叉树节点结构体
  5. {
  6. int data;
  7. struct node *left;
  8. struct node *right;
  9. }*binary;
  10. binary create_node()//创建节点并初始化
  11. {
  12. binary s=(binary)malloc(sizeof(struct node));
  13. if(NULL==s)
  14. return NULL;
  15. s->data=0;
  16. s->left=NULL;
  17. s->right=NULL;
  18. return s;
  19. }
  20. binary binary_tree()
  21. {
  22. int element;
  23. printf("please enter element(end==0):");
  24. scanf("%d",&element);
  25. if(0==element)
  26. return NULL;
  27. binary tree=create_node();
  28. tree->data=element;
  29. tree->left=binary_tree();
  30. tree->right=binary_tree();
  31. return tree;
  32. }
  33. void first_output(binary tree)
  34. {
  35. if(tree==NULL)
  36. return;
  37. printf("%d ",tree->data);
  38. first_output(tree->left);
  39. first_output(tree->right);
  40. }
  41. void mid_output(binary tree)
  42. {
  43. if(NULL==tree)
  44. return;
  45. mid_output(tree->left);
  46. printf("%d ",tree->data);
  47. mid_output(tree->right);
  48. }
  49. void last_output(binary tree)
  50. {
  51. if(NULL==tree)
  52. return;
  53. last_output(tree->left);
  54. last_output(tree->right);
  55. printf("%d ",tree->data);
  56. }
  57. void limit_tree(binary tree,int *n0,int *n1,int *n2)
  58. {
  59. if(NULL==tree)
  60. return;
  61. if(tree->left&&tree->right)
  62. ++*n2;
  63. else if(!tree->left && !tree->right)
  64. ++*n0;
  65. else
  66. ++*n1;
  67. limit_tree(tree->left,n0,n1,n2);
  68. limit_tree(tree->right,n0,n1,n2);
  69. }
  70. int high_tree(binary tree)
  71. {
  72. if(NULL==tree)
  73. return 0;
  74. int left=1+high_tree(tree->left);
  75. int right=1+high_tree(tree->right);
  76. return left>right?left:right;
  77. }
  78. int main(int argc, const char *argv[])
  79. {
  80. binary tree=binary_tree();//创建二叉树
  81. first_output(tree);//先序遍历
  82. puts("");
  83. mid_output(tree);//中序遍历
  84. puts("");
  85. last_output(tree);//后序遍历
  86. puts("");
  87. int n0=0,n1=0,n2=0;
  88. limit_tree(tree,&n0,&n1,&n2);//计算各个度的节点的个数;
  89. printf("n0=%d,n1=%d,n2=%d\n",n0,n1,n2);
  90. int high=high_tree(tree);//计算二叉树深度;
  91. printf("the high of the binary tree is:%d\n",high);
  92. return 0;
  93. }

以下图二叉树为例运行结果:

二叉树图:

运行:

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

闽ICP备14008679号