我正在尝试将二进制树转换为C#中的双链表。
DLL中节点的顺序必须按顺序遍历二叉树。
以下是代码:
public void BSTtoDLL(ref Node root,ref Node head,ref Node tail)
{
if (root == null) return;
BSTtoDLL(ref root.left,ref head,ref tail);
if (tail != null)
{
root.left = tail;
tail.right = root;
}
else
{
head = root;
}
tail = root;
BSTtoDLL(ref root.right,ref head, ref tail);
}
但是我得到了堆栈溢出异常?
我缺少什么?
答案 0 :(得分:0)
虽然inorder遍历没有问题,但代码的其余部分基本上是错误的。虽然left
和right
字段是树结构的本机部分,但您滥用它们作为双链表。结果是你使树结构无效,显然引入了一个圆圈,然后导致堆栈溢出。
如果你真的需要将这些引用保留在 Node
类本身中,你必须保持两对,如下所示:
treeLeft
,treeRight
- 用于树数据结构listPrev
,listNext
- 用于双链表结构(注意它是调用这些引用的常用约定上一个和 next )还有几件事需要考虑:
ref
ref
,而是在DoubleLinkedList
类上运行TreeNode<T>
和ListNode<T>
,其中T
表示有用的数据有效负载。< / LI>
答案 1 :(得分:-1)
public class TreeNode
{
public TreeNode Left { get; set; }
public int Data { get; set; }
public TreeNode Right { get; set; }
public TreeNode(int data)
{
this.Left = null;
this.Data = data;
this.Right = null;
}
}
public class DLLNode
{
public DLLNode Prev { get; set; }
public int Data { get; set; }
public DLLNode Next { get; set; }
public DLLNode(int data)
{
this.Data = data;
}
}
public class Tree
{
public TreeNode Root { get; set; }
public Tree()
{
// Creating a dummy tree;
Root = new TreeNode(10);
Root.Left = new TreeNode(12);
Root.Left.Left = new TreeNode(25);
Root.Left.Right = new TreeNode(30);
Root.Right = new TreeNode(15);
Root.Right.Left = new TreeNode(36);
}
}
public class DLL
{
private DLLNode Curr { get; set; }
public DLLNode Head { get; set; }
public void FromTree(Tree t)
{
ProcessInOrder(t.Root);
}
public void Display()
{
while(Head != null)
{
Console.Write(Head.Data + ", ");
Head = Head.Next;
}
}
private void ProcessInOrder(TreeNode n)
{
if(n != null)
{
ProcessInOrder(n.Left);
CreateDLLNode(n);
ProcessInOrder(n.Right);
}
}
private void CreateDLLNode(TreeNode n)
{
DLLNode node = new DLLNode(n.Data);
if(Curr == null)
{
Curr = Head = node;
}
else
{
Curr.Next = node;
node.Prev = Curr;
Curr = node;
}
}
}
DLL d = new DLL();
d.FromTree(new Tree());
d.Display();