File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
src/Algorithms/0099.recover-binary-search-tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments