-
Notifications
You must be signed in to change notification settings - Fork 112
/
099-RecoverBinarySearchTree.cs
47 lines (41 loc) · 1.32 KB
/
099-RecoverBinarySearchTree.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
//-----------------------------------------------------------------------------
// Runtime: 140ms
// Memory Usage:
// Link:
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
public class _099_RecoverBinarySearchTree
{
private Stack<TreeNode> stack = new Stack<TreeNode>();
private TreeNode prev = null;
private TreeNode first = null;
private TreeNode second = null;
private TreeNode current = null;
public void RecoverTree(TreeNode root)
{
current = root;
while (stack.Count > 0 || current != null)
{
while (current != null)
{
stack.Push(current);
current = current.left;
}
current = stack.Pop();
if (prev != null && current.val < prev.val)
{
if (first == null) first = prev;
second = current;
}
if (first != null && first.val < current.val) break;
prev = current;
current = current.right;
}
var temp = first.val;
first.val = second.val;
second.val = temp;
}
}
}