示例#1
0
        static void testAvlTree()
        {
            int treenodenum = 10;

            int[] vals = new int[treenodenum];
            for (int i = 0; i < treenodenum; i++)
            {
                vals[i] = i;
            }

            for (int i = 0; i < treenodenum; i++)
            {
                int idx1 = random.Next(treenodenum);
                int idx2 = random.Next(treenodenum);
                int tmp  = vals[idx1];
                vals[idx1] = vals[idx2];
                vals[idx2] = tmp;
            }

            Console.WriteLine("构建树节点:");
            printintarray(vals);
            Console.WriteLine("");

            AVLTree avltree = new AVLTree();

            avltree.Construct(vals);

            Console.WriteLine("先序遍历结果:");
            Console.WriteLine("递归调用先序遍历结果:");
            var sequence = avltree.DLRSequence();

            printBinaryNode(sequence);
            Console.WriteLine("");

            Console.WriteLine("中序遍历结果:");
            sequence = avltree.LDRSequence();
            printBinaryNode(sequence);
            Console.WriteLine("");

            for (int i = 0; i < treenodenum; i++)
            {
                var findval = random.Next(treenodenum);
                Console.WriteLine(String.Format("查找数字为:{0}", findval));
                var node = avltree.Find(findval);
                if (node == null)
                {
                    Console.WriteLine(String.Format("未能查找到数字:{0}", findval));
                }
                else
                {
                    Console.WriteLine(String.Format("成功查找到数字:{0}", node.nodeValue));
                }

                if (node != null)
                {
                    var bstval = node.nodeValue;
                    Console.WriteLine(String.Format("测试删除节点:{0}", bstval));
                    var bok = avltree.DelNode(node.nodeValue);
                    if (bok)
                    {
                        Console.WriteLine(String.Format("成功删除节点:{0}", bstval));
                    }
                    else
                    {
                        Console.WriteLine(String.Format("删除节点:{0} 失败", bstval));
                    }

                    Console.WriteLine("先序遍历结果:");
                    Console.WriteLine("递归调用先序遍历结果:");
                    sequence = avltree.DLRSequence();
                    printBinaryNode(sequence);
                    Console.WriteLine("");

                    Console.WriteLine("中序遍历结果:");
                    sequence = avltree.LDRSequence();
                    printBinaryNode(sequence);
                    Console.WriteLine("");
                }
            }
        }