1. <?php
    2. Class TreeNode {
    3. /** @var int $val */
    4. public $val = 0;
    5. /** @var TreeNode $left */
    6. public $left;
    7. /** @var TreeNode $right */
    8. public $right;
    9. public function __construct($val) {
    10. $this->val = $val;
    11. }
    12. }
    13. class Solution {
    14. public array $res = [];
    15. public function preorderTraversal($root) {
    16. if ($root) {
    17. array_push($this->res, $root->val);
    18. $this->inorderTraversal($root->left);
    19. $this->inorderTraversal($root->right);
    20. }
    21. return $this->res;
    22. }
    23. public function inorderTraversal($root) {
    24. if ($root) {
    25. $this->inorderTraversal($root->left);
    26. array_push($this->res, $root->val);
    27. $this->inorderTraversal($root->right);
    28. }
    29. return $this->res;
    30. }
    31. public function postorderTraversal($root) {
    32. if ($root) {
    33. $this->inorderTraversal($root->left);
    34. $this->inorderTraversal($root->right);
    35. array_push($this->res, $root->val);
    36. }
    37. return $this->res;
    38. }
    39. }
    40. /**
    41. * 1
    42. * / \
    43. * 2 3
    44. * / \ /
    45. * 4 5 6
    46. */
    47. $tree = new TreeNode(1);
    48. $tree->left = new TreeNode(2);
    49. $tree->left->left = new TreeNode(4);
    50. $tree->left->right = new TreeNode(5);
    51. $tree->right = new TreeNode(3);
    52. $tree->right->left = new TreeNode(6);
    53. $cls = new Solution();
    54. $r = $cls->preorderTraversal($tree);
    55. echo '前序遍历:' . implode(',', $r) . "\n";
    56. $cls1 = new Solution();
    57. $r = $cls1->inorderTraversal($tree);
    58. echo '中序遍历:' . implode(',', $r) . "\n";
    59. $cls2 = new Solution();
    60. $r = $cls2->postorderTraversal($tree);
    61. echo '后序遍历:' . implode(',', $r) . "\n";