-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBinarySearchTreeToDoubleLinkedList.cs
79 lines (61 loc) · 2.07 KB
/
BinarySearchTreeToDoubleLinkedList.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BinarySearchTreeToDoubleLinkedList
{
public class Node
{
public Node left;
public Node right;
public int data;
public Node(int d)
{
this.data = d;
}
// using divide and conquer techniques; another solution is to use node rotation
public static void convertBSTToDLL(Node root, ref Node header)
{
if (root == null)
{
header = null;
return;
}
Node lastNode = null;
convertBSTToDLLCore(root, ref lastNode);
// we need to get the header node; go upper to the last node and find the header
header = lastNode; // test cases: null, one node, more than one, ...
while (lastNode != null && lastNode.left !=null)
{
header = lastNode.left;
lastNode = lastNode.left;
}
}
public static void convertBSTToDLLCore(Node root, ref Node lastNodeInDLList)
{
if (root == null)
return;
Node currentNode = root;
convertBSTToDLLCore(root.left, ref lastNodeInDLList);
currentNode.left = lastNodeInDLList;
if (lastNodeInDLList != null) // avoid crash
lastNodeInDLList.right = currentNode;
lastNodeInDLList = currentNode;
convertBSTToDLLCore(root.right, ref lastNodeInDLList);
return;
}
static void Main(string[] args)
{
Node root = new Node(10);
root.left = new Node(8);
root.left.left = new Node(7);
root.left.right = new Node(9);
root.right = new Node(12);
root.right.left = new Node(11);
root.right.right = new Node(13);
Node header = null;
convertBSTToDLL(root, ref header);
}
}
}