예제 #1
0
        // expression string is always correct
        // digits and operations, while any expression or sub-expression is in ()
        // ((2*3)+((8/2)*4))
        public static BinNode <char> BuildExprTree(string expr)
        {
            Stack <BinNode <char> > nodes = new Stack <BinNode <char> >();

            foreach (var c in expr)
            {
                if (c == ')')
                {
                    BinNode <char> right = nodes.Pop();
                    BinNode <char> oper  = nodes.Pop();
                    BinNode <char> left  = nodes.Pop();
                    oper.SetLeft(left);
                    oper.SetRight(right);
                    nodes.Push(oper);
                }
                else if (c != '(')
                {
                    nodes.Push(new BinNode <char>(c));
                }
            }
            return(nodes.Pop());
        }
예제 #2
0
        static void Main(string[] args)
        {
            Console.Write("Press a key (enter a char): ");
            char ch1 = Console.ReadKey().KeyChar;

            Console.WriteLine();
            Console.WriteLine(ch1);
            ch1 = (char)(ch1 + 1);
            Console.WriteLine(ch1);
            BinNode <char> a = new BinNode <char>('a');
            BinNode <char> b = new BinNode <char>('b');
            BinNode <char> c = new BinNode <char>('c');
            BinNode <char> d = new BinNode <char>('d');
            BinNode <char> e = new BinNode <char>('e');
            BinNode <char> f = new BinNode <char>('f');

            a.SetLeft(b);
            a.SetRight(c);
            b.SetRight(d);
            c.SetLeft(e);
            c.SetRight(f);
            Console.WriteLine("Preorder:");
            PrintPreOrder(a);
            Console.WriteLine();
            Console.WriteLine("Inorder:");
            PrintInOrder(a);
            Console.WriteLine();
            Console.WriteLine("Postorder:");
            PrintPostOrder(a);
            Console.WriteLine();
            Console.WriteLine("Travers by Levels:");
            TraverseByLevel(a);
            Console.WriteLine();

            //Console.WriteLine(ComputeExprTree(BuildExprTree("((2*3)+((8/2)*4))")));
        }