diff --git a/problems/二叉树的递归遍历.md b/problems/二叉树的递归遍历.md index a1d49e98..f2a97f4d 100644 --- a/problems/二叉树的递归遍历.md +++ b/problems/二叉树的递归遍历.md @@ -671,6 +671,62 @@ public void Traversal(TreeNode cur, IList res) } ``` +### PHP +```php +// 144.前序遍历 +function preorderTraversal($root) { + $output = []; + $this->traversal($root, $output); + return $output; +} + +function traversal($root, array &$output) { + if ($root->val === null) { + return; + } + + $output[] = $root->val; + $this->traversal($root->left, $output); + $this->traversal($root->right, $output); +} +``` +```php +// 94.中序遍历 +function inorderTraversal($root) { + $output = []; + $this->traversal($root, $output); + return $output; +} + +function traversal($root, array &$output) { + if ($root->val === null) { + return; + } + + $this->traversal($root->left, $output); + $output[] = $root->val; + $this->traversal($root->right, $output); +} +``` +```php +// 145.后序遍历 +function postorderTraversal($root) { + $output = []; + $this->traversal($root, $output); + return $output; +} + +function traversal($root, array &$output) { + if ($root->val === null) { + return; + } + + $this->traversal($root->left, $output); + $this->traversal($root->right, $output); + $output[] = $root->val; +} +``` +