예제 #1
0
        public static void Main()
        {
            //   1
            //  / \
            // 2   3

            // in-order:  213
            // preorder:  123
            // postorder: 231

            var root = new Node <int>(1,
                                      new Node <int>(2), new Node <int>(3));

            // C++ style
            var it = new InOrderIterator <int>(root);

            while (it.MoveNext())
            {
                Write(it.Current.Value);
                Write(',');
            }
            WriteLine();

            // C# style
            var tree = new BinaryTree <int>(root);

            WriteLine(string.Join(",", tree.NaturalInOrder.Select(x => x.Value)));

            // duck typing!
            foreach (var node in tree)
            {
                WriteLine(node.Value);
            }
        }
예제 #2
0
        public static void Main()
        {
            //   1
            //  / \
            // 2   3

            // in-order:  213
            // preorder:  123
            // postorder: 231

            var root = new Node <int>(1,
                                      new Node <int>(2), new Node <int>(3));

            // C++ style - clumsy
            var it = new InOrderIterator <int>(root);

            while (it.MoveNext())
            {
                Write(it.Current.Value);
                Write(',');
            }
            WriteLine();

            // C# style - more natural
            var tree = new BinaryTree1 <int>(root);

            WriteLine(string.Join(",", tree.NaturalInOrder.Select(x => x.Value)));

            // duck typing! tree is enumerable when it has GetEnumerator() that returns an iterator
            // an iterator is something that has Current and MoveNext()
            foreach (var node in new BinaryTree3 <int>(root))
            {
                WriteLine(node.Value);
            }

            // duck typing, BinaryTree2 doesn't implement IEnumerable
            foreach (var node in new BinaryTree2 <int>(root))
            {
                WriteLine(node.Value);
            }
        }