二叉树遍历 前中后

旧城等待, 2022-08-18 15:27 222阅读 0赞

这里写图片描述

  1. #include <iostream>
  2. using namespace std;
  3. struct t{
  4. int v;
  5. struct t * left;
  6. struct t * right;
  7. };
  8. void preorder(struct t *tree){
  9. if (tree == NULL){
  10. return;
  11. }
  12. cout << "i'm root " << tree->v << endl;
  13. preorder(tree->left);
  14. preorder(tree->right);
  15. }
  16. void backorder(struct t *tree){
  17. if (tree == NULL){
  18. return;
  19. }
  20. backorder(tree->left);
  21. backorder(tree->right);
  22. cout << "i'm root " << tree->v << endl;
  23. }
  24. void midorder(struct t *tree){
  25. if (tree == NULL){
  26. return;
  27. }
  28. midorder(tree->left);
  29. cout << "i'm root " << tree->v << endl;
  30. midorder(tree->right);
  31. }
  32. int main()
  33. {
  34. struct t trees[5]={};
  35. cout << "hello world" << endl;
  36. trees[0].v = 1;
  37. trees[1].v = 3;
  38. trees[2].v = 5;
  39. trees[3].v = 7;
  40. trees[4].v = 9;
  41. for (int i=0; i<5; i++){
  42. cout << trees[i].v << endl;
  43. }
  44. trees[0].left = &trees[1];
  45. trees[0].right = &trees[2];
  46. trees[1].left = &trees[3];
  47. trees[1].right = &trees[4];
  48. cout << "preorder" << endl;
  49. preorder(trees);
  50. cout << "backorder" << endl;
  51. backorder(trees);
  52. cout << "midorder" << endl;
  53. midorder(trees);
  54. return 0;
  55. }
  56. [root@ bigo]# g++ tree.cpp
  57. [root@ bigo]#
  58. [root@ bigo]#
  59. [root@ bigo]# ./a.out
  60. hello world
  61. 1
  62. 3
  63. 5
  64. 7
  65. 9
  66. preorder
  67. i'm root 1
  68. i'm root 3
  69. i'm root 7
  70. i'm root 9
  71. i'm root 5
  72. backorder
  73. i'm root 7
  74. i'm root 9
  75. i'm root 3
  76. i'm root 5
  77. i'm root 1
  78. midorder
  79. i'm root 7
  80. i'm root 3
  81. i'm root 9
  82. i'm root 1
  83. i'm root 5
  84. [root@ bigo]#

我去滴滴面试,没答出这道题,遗憾。

发表评论

表情:
评论列表 (有 0 条评论,222人围观)

还没有评论,来说两句吧...

相关阅读

    相关

    首先理解前中后序遍历。 他们是相对根节点的遍历前后来决定的; 也就是遍历顺序如果是前序遍历 : 就是按先遍历根节点,在遍历左节点,再遍历右节点; 从下面的二叉树体会一