示例#1
0
        public static void Test()
        {
            ///      +
            ///    /   \
            ///   *     -
            ///  / \   / \
            /// 5  4 100 20
            /// result: 5*4 + (100-20) = 100
            BinaryNodeExpression root = new BinaryNodeExpression("+");

            root.Left        = new BinaryNodeExpression("*");
            root.Left.Left   = new BinaryNodeExpression("5");
            root.Left.Right  = new BinaryNodeExpression("4");
            root.Right       = new BinaryNodeExpression("-");
            root.Right.Left  = new BinaryNodeExpression("100");
            root.Right.Right = new BinaryNodeExpression("20");

            Console.Write("Tree 1 result: " + EvaluateTree(root));

            BinaryNodeExpression root2 = new BinaryNodeExpression("+");

            root2.Left              = new BinaryNodeExpression("*");
            root2.Left.Left         = new BinaryNodeExpression("5");
            root2.Left.Right        = new BinaryNodeExpression("4");
            root2.Right             = new BinaryNodeExpression("-");
            root2.Right.Left        = new BinaryNodeExpression("100");
            root2.Right.Right       = new BinaryNodeExpression("/");
            root2.Right.Right.Left  = new BinaryNodeExpression("20");
            root2.Right.Right.Right = new BinaryNodeExpression("2");
            Console.Write("\nTree 2 result: " + EvaluateTree(root2));
        }
        /// <summary>
        ///      -
        ///    /   \
        ///   +     *
        ///  / \   / \ 
        /// a   b *   g
        ///      / \
        ///     e   f
        /// infix expression is
        /// a + b - e* f * g
        /// </summary>
        public static void PrintExpression()
        {
            String postfix            = "ab+ef*g*-";
            BinaryNodeExpression root = ConstructTree(postfix);

            Console.WriteLine("infix expression is");
            PrintExpressionTreeInOrder(root);
        }
 // Utility function to do inorder traversal
 private static void PrintExpressionTreeInOrder(BinaryNodeExpression t)
 {
     if (t != null)
     {
         PrintExpressionTreeInOrder(t.Left);
         Console.Write(t.Value + " ");
         PrintExpressionTreeInOrder(t.Right);
     }
 }
        // Returns root of constructed tree for given
        // postfix expression
        /// <summary>
        /// Construction of Expression Tree:
        /// Now For constructing expression tree we use a stack.We loop through input expression and do following for every character.
        /// 1) If character is operand push that into stack
        /// 2) If character is operator pop two values from stack make them its child and push current node again.
        /// At the end only element of stack will be root of expression tree.
        /// </summary>
        /// <param name="postfix"></param>
        /// <returns></returns>
        public static BinaryNodeExpression ConstructTree(string postfix)
        {
            Stack <BinaryNodeExpression> st = new Stack <BinaryNodeExpression>();
            BinaryNodeExpression         t, t1, t2;

            // Traverse through every character of
            // input expression
            var postFixCharArray = postfix.ToCharArray();

            for (int i = 0; i < postFixCharArray.Length; i++)
            {
                // If operand, simply push into stack
                if (!IsOperator(postFixCharArray[i].ToString()))
                {
                    t = new BinaryNodeExpression(postFixCharArray[i].ToString());
                    st.Push(t);
                }
                else // operator
                {
                    t = new BinaryNodeExpression(postFixCharArray[i].ToString());

                    // Pop two top nodes
                    // Store top
                    t1 = st.Pop();      // Remove top
                    t2 = st.Pop();

                    //  make them children
                    t.Right = t1;
                    t.Left  = t2;

                    st.Push(t);
                }
            }

            //  only element will be root of expression
            // tree
            t = st.Peek();
            st.Pop();

            return(t);
        }
示例#5
0
        private static int EvaluateTree(BinaryNodeExpression root)
        {
            // empty tree
            if (root == null)
            {
                return(0);
            }

            // leaf node i.e, an integer
            if (root.Left == null && root.Right == null)
            {
                return(Convert.ToInt32(root.Value));
            }

            // Evaluate left subtree
            int l_val = EvaluateTree(root.Left);

            // Evaluate right subtree
            int r_val = EvaluateTree(root.Right);

            // Check which operator to apply
            if (root.Value == "+")
            {
                return(l_val + r_val);
            }

            if (root.Value == "-")
            {
                return(l_val - r_val);
            }

            if (root.Value == "*")
            {
                return(l_val * r_val);
            }

            return(l_val / r_val);
        }
示例#6
0
        public static List <List <int> > verticalOrder(BinaryNodeExpression root)
        {
            List <List <int> >            result = new List <List <int> >();
            Dictionary <int, List <int> > dic    = new Dictionary <int, List <int> >();
            int minHorizontalDistnace            = int.MaxValue;
            int maxHorizontalDistnace            = int.MinValue;

            Queue <NodeWithHorizontalDistance> q = new Queue <NodeWithHorizontalDistance>();

            q.Enqueue(new NodeWithHorizontalDistance(root, 0));

            while (q.Count > 0)
            {
                NodeWithHorizontalDistance cur = q.Dequeue();
                dic.Add(cur.horizontalDistnace, new List <int> {
                    Convert.ToInt32(cur.root.Value)
                });
                minHorizontalDistnace = Math.Min(minHorizontalDistnace, cur.horizontalDistnace);
                maxHorizontalDistnace = Math.Max(maxHorizontalDistnace, cur.horizontalDistnace);

                if (cur.root.Left != null)
                {
                    q.Enqueue(new NodeWithHorizontalDistance(cur.root.Left, cur.horizontalDistnace - 1));
                }

                if (cur.root.Right != null)
                {
                    q.Enqueue(new NodeWithHorizontalDistance(cur.root.Right, cur.horizontalDistnace + 1));
                }
            }

            for (int i = minHorizontalDistnace; i <= maxHorizontalDistnace; i++)
            {
                result.Add(dic.GetValueOrDefault(i));
            }
            return(result);
        }
示例#7
0
 public NodeWithHorizontalDistance(BinaryNodeExpression root, int horizontalDistnace)
 {
     this.root = root;
     this.horizontalDistnace = horizontalDistnace;
 }
 public BinaryNodeExpression(string value)
 {
     this.Value = value;
     this.Left  = this.Right = null;
 }