Skip to content

Commit 023f19e

Browse files
committed
Add solution 99.
1 parent daabfe7 commit 023f19e

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* class TreeNode {
4+
* public $val = null;
5+
* public $left = null;
6+
* public $right = null;
7+
* function __construct($value) { $this->val = $value; }
8+
* }
9+
*/
10+
class Solution {
11+
12+
/**
13+
* @param TreeNode $root
14+
* @return NULL
15+
*/
16+
function recoverTree($root) {
17+
$stack = [];
18+
$current = $root; $prev = null; $first = null; $second = null;
19+
while ($current != null || count($stack) != 0) {
20+
while ($current != null) {
21+
array_push($stack, $current);
22+
$current = $current->left;
23+
}
24+
$current = array_pop($stack);
25+
if ($prev != null && $current->val < $prev->val) {
26+
if ($first == null) $first = $prev;
27+
$second = $current;
28+
}
29+
$prev = $current; $current = $current->right;
30+
}
31+
// swap
32+
$temp = $first->val; $first->val = $second->val; $second->val = $temp;
33+
}
34+
}

0 commit comments

Comments
 (0)