二叉树的递归遍历 add php version

This commit is contained in:
alanx15a2
2024-05-30 12:00:12 +08:00
parent 5df89282d2
commit 692f63a77e

View File

@ -671,6 +671,62 @@ public void Traversal(TreeNode cur, IList<int> 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;
}
```
<p align="center">
<a href="https://programmercarl.com/other/kstar.html" target="_blank">