Description:
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
Example:
1 2 3 4 5 6 7 8
| Input: root = [1,2,2,3,4,4,3] 1 / \ 2 2 / \ / \ 3 4 4 3
Output: true
|
1 2 3 4 5 6 7 8
| Input: root = [1,2,2,null,3,null,3] 1 / \ 2 2 \ \ 3 3
Output: false
|
Follow up: Could you solve it both recursively and iteratively?
Similar Question: 94.binary-tree-inorder-traversal
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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| <?php
namespace LeetCode\SymmetricTree;
class Solution {
protected $answer = true;
public function isSymmetric($root) { if (is_null($root->val)) { return true; }
if (is_null($root->left) && is_null($root->right)) { return true; }
$this->checkSysmmetric($root->left, $root->right); return $this->answer; }
private function checkSysmmetric($leftTree, $rightTree) { if ($leftTree->val !== $rightTree->val) { return $this->answer = false; }
if ( $leftTree->left instanceof TreeNode && $rightTree->right instanceof TreeNode ) { $this->checkSysmmetric($leftTree->left, $rightTree->right); }
if ( $leftTree->right instanceof TreeNode && $rightTree->left instanceof TreeNode ) { $this->checkSysmmetric($leftTree->right, $rightTree->left); }
if ($this->isNullAmountOdd($leftTree->left, $rightTree->right)) { return $this->answer = false; }
if ($this->isNullAmountOdd($leftTree->right, $rightTree->left)) { return $this->answer = false; } }
private function isNullAmountOdd($a, $b) { $nullAmount = 0;
if (is_null($a)) { $nullAmount++; }
if (is_null($b)) { $nullAmount++; }
return ($nullAmount % 2 == 1); } }
|
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 56 57 58 59 60
| <?php
namespace LeetCode\SymmetricTree;
class Solution {
protected $stack = [];
public function isSymmetric($root) { if (is_null($root->val)) { return true; }
$this->stack[] = [$root->left, $root->right];
while (count($this->stack) > 0) { $pop = array_pop($this->stack); $left = $pop[0]; $right = $pop[1];
if (is_null($left) && is_null($right)) { continue; }
if (is_null($left) || is_null($right)) { return false; }
if ($left->val == $right->val) { $this->stack[] = [$left->left, $right->right]; $this->stack[] = [$left->right, $right->left]; } else { return false; } }
return true; } }
|
ʕ •ᴥ•ʔ:Iterating的作法,有體會到要利用Stack當存檔點,但具體的while條件沒有想出來。