二叉查找树变成有序的双向列表
通过中序遍历可以得到一个有序的序列,不创建一个节点实现有序双向列表。
/// <summary>
/// 二叉查找树变成有序的双向链表,不创建新的节点
/// </summary>
public class BST2LinkList
{
public static void Convert()
{
Node[] tree = CreateBST();
Node head = null;
MidddleOrderSearch(tree, 0, ref head);
Console.Read();
}
public static void MidddleOrderSearch(Node[] tree, int cur, ref Node head)
{
//左子结点
int left = (cur + 1)*2 - 1;
if (left < tree.Length )
{
MidddleOrderSearch(tree, left, ref head); //递归遍历左子树
}
//处理当前节点
if (head == null)
{
head = tree[cur];
}
else
{
AppendNode(head, tree[cur]);
}
//右子结点
int right = (cur + 1) * 2;
if (right < tree.Length )
{
MidddleOrderSearch(tree, right,ref head);//递归遍历右子树
}
}
public static void AppendNode(Node head, Node node)
{
Node tmp = head;
while (tmp.Next != null)
{
tmp = tmp.Next;
}
tmp.Next = node;
node.Pre = tmp;
}
public static void DisplayLinkList(Node head)
{
do
{
Console.Write(head.Num + ",");
head = head.Next;
}
while (head != null);
Console.WriteLine();
}
public static void DisplayLinkListFromTail(Node tail)
{
while (tail != null&&tail.Next!=null) { tail = tail.Next; };
do
{
Console.Write(tail.Num + ",");
tail = tail.Pre;
}
while (tail != null);
Console.WriteLine();
}
public static Node[] CreateBST()
{
Node[] tree=new Node[9];
int[] arrayNum = { 6,4,8,2,5,7,9,1,3};
for (int i = 0; i < arrayNum.Length; i++)
{
Node tmp = new Node() { Num=arrayNum[i]};
tree[i] = tmp;
}
return tree;
}
public class Node
{
public int Num;
public Node Pre;
public Node Next;
}
}
浙公网安备 33010602011771号