Description:
Given a binary tree, return the inorder traversal of its nodes’ values.
Example:
1 2 3 4 5 6 7 8
| Input: [1,null,2,3] 1 \ 2 / 3
Output: [1,3,2]
|
Follow up: Recursive solution is trivial, could you do it iteratively?
說明:
1 2 3 4 5
| 4 / \ 2 6 / \ / \ 1 3 5 7
|
遍歷方式 |
輸出結果 |
搜尋演算法 |
Pre-Order Traversal |
4213657 |
Depth-first Search |
In-Order Traversal |
1234567 |
Depth-first Search |
Post-Order Traversal |
1325764 |
Depth-first Search |
Level-Order Traversal |
4261357 |
Breadth-first Search |
Pre-, In-, Post- 是指parent node相對於child node的順序。
而Level-則是依照層級關係。
First Answer (Recursive):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| <?php
namespace LeetCode\BinaryTreeInorderTraversal;
class Solution {
protected $answer = [];
public function inorderTraversal($root) { $this->findAnswer($root); return $this->answer; }
private function findAnswer($root) {
if (!is_null($root->left)) { $this->findAnswer($root->left); }
$this->answer[] = $root->val;
if (!is_null($root->right)) { $this->findAnswer($root->right); } } }
|
Other Answer (Iterating + Stack):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| <?php
namespace LeetCode\BinaryTreeInorderTraversal;
class Solution {
protected $answer = [];
protected $stack = [];
public function inorderTraversal($root) { $this->findAnswer($root); return $this->answer; }
private function findAnswer($root) { while (count($this->stack) > 0 || !is_null($root)) { if (!is_null($root)) { $this->stack[] = $root; $root = $root->left; } else { $pop = array_pop($this->stack); $this->answer[] = $pop->val;
if (!is_null($pop->right)) { $root = $pop->right; } } } } }
|
ʕ •ᴥ•ʔ:還有看到一種Morris Traversal的方法,之後遇到再補充。