Skip to content

Commit 692f63a

Browse files
committed
二叉树的递归遍历 add php version
1 parent 5df8928 commit 692f63a

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

problems/二叉树的递归遍历.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -671,6 +671,62 @@ public void Traversal(TreeNode cur, IList<int> res)
671671
}
672672
```
673673

674+
### PHP
675+
```php
676+
// 144.前序遍历
677+
function preorderTraversal($root) {
678+
$output = [];
679+
$this->traversal($root, $output);
680+
return $output;
681+
}
682+
683+
function traversal($root, array &$output) {
684+
if ($root->val === null) {
685+
return;
686+
}
687+
688+
$output[] = $root->val;
689+
$this->traversal($root->left, $output);
690+
$this->traversal($root->right, $output);
691+
}
692+
```
693+
```php
694+
// 94.中序遍历
695+
function inorderTraversal($root) {
696+
$output = [];
697+
$this->traversal($root, $output);
698+
return $output;
699+
}
700+
701+
function traversal($root, array &$output) {
702+
if ($root->val === null) {
703+
return;
704+
}
705+
706+
$this->traversal($root->left, $output);
707+
$output[] = $root->val;
708+
$this->traversal($root->right, $output);
709+
}
710+
```
711+
```php
712+
// 145.后序遍历
713+
function postorderTraversal($root) {
714+
$output = [];
715+
$this->traversal($root, $output);
716+
return $output;
717+
}
718+
719+
function traversal($root, array &$output) {
720+
if ($root->val === null) {
721+
return;
722+
}
723+
724+
$this->traversal($root->left, $output);
725+
$this->traversal($root->right, $output);
726+
$output[] = $root->val;
727+
}
728+
```
729+
674730

675731
<p align="center">
676732
<a href="https://programmercarl.com/other/kstar.html" target="_blank">

0 commit comments

Comments
 (0)