forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cs
62 lines (59 loc) · 1.46 KB
/
Solution.cs
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
public class Solution {
private TreeNode last, first, second;
public void RecoverTree(TreeNode root) {
Traverse(root);
var temp = first.val;
first.val = second.val;
second.val = temp;
}
private void Traverse(TreeNode root)
{
var current = root;
TreeNode temp;
while (current != null)
{
if (current.left == null)
{
Visit(current);
current = current.right;
}
else
{
temp = current.left;
while (temp.right != null && temp.right != current)
{
temp = temp.right;
}
if (temp.right == null)
{
temp.right = current;
current = current.left;
}
else
{
Visit(current);
temp.right = null;
current = current.right;
}
}
}
}
private void Visit(TreeNode node)
{
if (last != null)
{
if (node.val < last.val)
{
if (first == null)
{
first = last;
}
}
if (first != null && node.val < first.val)
{
second = node;
}
}
last = node;
}
}