1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace leetcode; |
||
6 | |||
7 | use leetcode\util\TreeNode; |
||
8 | |||
9 | class BinaryTreeInorderTraversal |
||
10 | { |
||
11 | public static function inorderTraversal(TreeNode $root): array |
||
12 | { |
||
13 | if (empty($root)) { |
||
14 | return []; |
||
15 | } |
||
16 | [$ans, $curr, $stack] = [[], $root, []]; |
||
17 | while ($curr || $stack) { |
||
18 | while ($curr) { |
||
19 | array_push($stack, $curr); |
||
20 | $curr = $curr->left; |
||
21 | } |
||
22 | /** @var \leetcode\util\TreeNode $curr */ |
||
23 | $curr = array_pop($stack); |
||
24 | if ($curr->val) { |
||
25 | array_push($ans, $curr->val); |
||
26 | } |
||
27 | $curr = $curr->right; |
||
28 | } |
||
29 | |||
30 | return $ans; |
||
31 | } |
||
32 | |||
33 | public static function inorderTraversal2(TreeNode $root): array |
||
34 | { |
||
35 | if (empty($root)) { |
||
36 | return []; |
||
37 | } |
||
38 | $ans = []; |
||
39 | self::helper($root, $ans); |
||
40 | |||
41 | return $ans; |
||
42 | } |
||
43 | |||
44 | private static function helper(TreeNode $root, array & $arr): void |
||
45 | { |
||
46 | if ($root) { |
||
0 ignored issues
–
show
introduced
by
![]() |
|||
47 | if ($root->left) { |
||
48 | self::helper($root->left, $arr); |
||
49 | } |
||
50 | if ($root->val) { |
||
51 | array_push($arr, $root->val); |
||
52 | } |
||
53 | if ($root->right) { |
||
54 | self::helper($root->right, $arr); |
||
55 | } |
||
56 | } |
||
57 | } |
||
58 | } |
||
59 |