-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0426-ConvertBinarySearchTreeToSortedDoublyLinkedList.cs
91 lines (75 loc) · 1.94 KB
/
0426-ConvertBinarySearchTreeToSortedDoublyLinkedList.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//-----------------------------------------------------------------------------
// Runtime: 96ms
// Memory Usage: 25 MB
// Link: https://leetcode.com/submissions/detail/368928169/
//-----------------------------------------------------------------------------
namespace LeetCode
{
/*
// Definition for a Node.
public class Node {
public int val;
public Node left;
public Node right;
public Node() {}
public Node(int _val) {
val = _val;
left = null;
right = null;
}
public Node(int _val,Node _left,Node _right) {
val = _val;
left = _left;
right = _right;
}
}
*/
public class _0426_ConvertBinarySearchTreeToSortedDoublyLinkedList
{
private Node first;
private Node last;
public Node TreeToDoublyList(Node root)
{
if (root == null) return null;
Helper(root);
first.left = last;
last.right = first;
return first;
}
private void Helper(Node node)
{
if (node == null) return;
Helper(node.left);
if (last != null)
{
last.right = node;
node.left = last;
}
else
{
first = node;
}
last = node;
Helper(node.right);
}
public class Node
{
public int val;
public Node left;
public Node right;
public Node() { }
public Node(int _val)
{
val = _val;
left = null;
right = null;
}
public Node(int _val, Node _left, Node _right)
{
val = _val;
left = _left;
right = _right;
}
}
}
}