/
101.symmetric-tree.php
68 lines (58 loc) · 1.37 KB
/
101.symmetric-tree.php
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
<?php
namespace LeetCode\SymmetricTree;
/*
* @lc app=leetcode id=101 lang=php
*
* [101] Symmetric Tree
*/
// @lc code=start
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($val = 0, $left = null, $right = null) {
* $this->val = $val;
* $this->left = $left;
* $this->right = $right;
* }
* }
*/
class Solution
{
/**
* @var array
*/
protected $stack = [];
/**
* @param TreeNode $root
* @return bool
*/
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;
}
}
// @lc code=end