<?phpClass TreeNode { /** @var int $val */ public $val = 0; /** @var TreeNode $left */ public $left; /** @var TreeNode $right */ public $right; public function __construct($val) { $this->val = $val; }}class Solution { public array $res = []; public function preorderTraversal($root) { if ($root) { array_push($this->res, $root->val); $this->inorderTraversal($root->left); $this->inorderTraversal($root->right); } return $this->res; } public function inorderTraversal($root) { if ($root) { $this->inorderTraversal($root->left); array_push($this->res, $root->val); $this->inorderTraversal($root->right); } return $this->res; } public function postorderTraversal($root) { if ($root) { $this->inorderTraversal($root->left); $this->inorderTraversal($root->right); array_push($this->res, $root->val); } return $this->res; }}/** * 1 * / \ * 2 3 * / \ / * 4 5 6 */$tree = new TreeNode(1);$tree->left = new TreeNode(2);$tree->left->left = new TreeNode(4);$tree->left->right = new TreeNode(5);$tree->right = new TreeNode(3);$tree->right->left = new TreeNode(6);$cls = new Solution();$r = $cls->preorderTraversal($tree);echo '前序遍历:' . implode(',', $r) . "\n";$cls1 = new Solution();$r = $cls1->inorderTraversal($tree);echo '中序遍历:' . implode(',', $r) . "\n";$cls2 = new Solution();$r = $cls2->postorderTraversal($tree);echo '后序遍历:' . implode(',', $r) . "\n";