mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
二叉树的递归遍历 add php version
This commit is contained in:
@ -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">
|
||||
|
Reference in New Issue
Block a user