二叉查找树转换成有序的双向链表

首先对于二叉查找树的定义和性质,以及如何得到二叉查找树某个节点的子树下的最大值和最小值和插入一个值的内容可以参考这两篇文章:

1http://www.cnblogs.com/chenping-987123/archive/2010/09/25/1834341.html

2http://www.cnblogs.com/chenping-987123/archive/2010/09/26/1836133.html

现在有一个二叉查找树如下所示:

 

insert 9 这个节点的时候

 

然后可以要输出的双向链表为:1 2 3 4 5 6 9 10 12

关于双向链表的知识,在数据结构的书中都有了很好的解释。

具体的程序如下:

BSTreeToList(root);

            Console.WriteLine("********************BSTreeToList***************");

            while (root.left != null)

            {

                root = root.left;

            }

            while (root != null)

            {

                Console.Write(root._value.ToString() + " ");

                root = root.right;

            }

private static void BSTreeToList(MyNode root)

        {

            if (root.left != null)

            {

                BSTreeToList(root.left);

            }

            if (root.right != null)

            {

                BSTreeToList(root.right);

            }

            MyNode max = TreeMax(root.left);

            MyNode min = TreeMin(root.right);

            if (max != null)

            {

                max.right = root;

            }

           root.left = max;

           if (min != null)

           {

               min.left = root;

           }

            root.right = min;

        }

posted @ 2010-10-14 20:28  chenping2008  阅读(1387)  评论(0编辑  收藏  举报