PHP 前序、中序、后序遍历二叉树

二叉树遍历

  • 前序:ABDEGIHCF
  • 中序:DBGIEHACF
  • 后序:DIGHEBFCA

答案

  1. <?php
  2. class Node
  3. {
  4. public $data = null;
  5. public $left = null;
  6. public $right = null;
  7. }
  8. $A = new Node();
  9. $B = clone $A;
  10. $C = clone $A;
  11. $D = clone $A;
  12. $E = clone $A;
  13. $F = clone $A;
  14. $G = clone $A;
  15. $H = clone $A;
  16. $I = clone $A;
  17. $A->data = 'A';
  18. $B->data = 'B';
  19. $C->data = 'C';
  20. $D->data = 'D';
  21. $E->data = 'E';
  22. $F->data = 'F';
  23. $G->data = 'G';
  24. $H->data = 'H';
  25. $I->data = 'I';
  26. $A->left = $B;
  27. $A->right = $C;
  28. $B->left = $D;
  29. $B->right = $E;
  30. $E->left = $G;
  31. $E->right = $H;
  32. $G->right = $I;
  33. $C->right = $F;
  34. /**
  35. * 前序遍历: 中左右
  36. * 中序遍历: 左中右
  37. * 后序遍历: 左右中
  38. */
  39. function eatBtree($node)
  40. {
  41. if ($node && $node->data) {
  42. eatBtree($node->left);
  43. eatBtree($node->right);
  44. echo $node->data; //把这一行的位置换一换就能实现遍历方式的转变,放到最后是后序,放到最前是前序,放到中间是中序
  45. }
  46. }
  47. eatBtree($A);
  48. /**
  49. * 层序遍历会用到队列
  50. */
  51. function eatBtree2($node)
  52. {
  53. $list[] = $node;
  54. while (count($list) > 0) {
  55. $cur = array_shift($list);
  56. if ($cur) {
  57. echo $cur->data;
  58. if ($cur->left) {
  59. $list[] = $cur->left;
  60. }
  61. if ($cur->right) {
  62. $list[] = $cur->right;
  63. }
  64. }
  65. }
  66. }
  67. eatBtree2($A);

参考资料