二叉树实现四则运算
using System; using System.Collections.Generic; namespace 表达式树四则运算 { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); Express = Console.ReadLine(); List<Node> nodeList = GetNode(); var head = CreateTree(nodeList); int result= PreOrderCalc(head); Console.WriteLine("{0}={1}", Express, result); Console.Read(); } private static int _currentIndex; private static string Express; public static List<Node> GetNode() { List<Node> nodeList = new List<Node>(); int digitCount = 0; while (_currentIndex < Express.Length) { if (Char.IsDigit(Express[_currentIndex])) { digitCount++; _currentIndex++; } else { nodeList.Add(new Node(Convert.ToInt32( Express.Substring(_currentIndex - digitCount, digitCount)))); nodeList.Add(new Node( Express[_currentIndex])); _currentIndex++; digitCount = 0; } } if(_currentIndex== Express.Length) { nodeList.Add(new Node(Convert.ToInt32(Express.Substring(_currentIndex - digitCount, digitCount)))); } return nodeList; } private static int GetPriority(char optr) { if (optr == '+' || optr == '-') { return 1; } else if (optr == '*' || optr == '/') { return 2; } else { return 0; } } private static Node CreateTree(List<Node> nodeList) { Node head = null; foreach(var node in nodeList) { if (head == null) { head = node; } else if (head.IsOptr == false) // 根节点为数字,当前节点为根,原根节点变为左孩子 { node.Left = head; head = node; } else if (node.IsOptr == false) // 如果当前节点是数字 { // 当前节点沿右路插入最右边成为右孩子 Node tempNode = head; while (tempNode.Right != null) { tempNode = tempNode.Right; } tempNode.Right = node; } else // 如果当前节点是运算符 { if (GetPriority((char)node.Data) <= GetPriority((char)head.Data)) // 优先级低则成为根,原二叉树成为插入节点的左子树 { node.Left = head; head = node; } else // 优先级高则成为根节点的右子树,原右子树成为插入节点的左子树 { node.Left = head.Right; head.Right = node; } } } return head; } private static int PreOrderCalc(Node node) { int num1, num2; if (node.IsOptr) { // 递归先序遍历计算num1 num1 = PreOrderCalc(node.Left); // 递归先序遍历计算num2 num2 = PreOrderCalc(node.Right); char optr = (char)node.Data; switch (optr) { case '+': node.Data = num1 + num2; break; case '-': node.Data = num1 - num2; break; case '*': node.Data = num1 * num2; break; case '/': if (num2 == 0) { throw new DivideByZeroException("除数不能为0!"); } node.Data = num1 / num2; break; } } return node.Data; } } class Node { public Node(int data) { Data = data; IsOptr = false; } public Node(char optr) { IsOptr = true; Data = optr; } public bool IsOptr { get; set; } public int Data { get; set; } public char Optr { get; set; } public Node Left { get; set; } public Node Right { get; set; } public override string ToString() { if (IsOptr) { return Optr.ToString(); } return Data.ToString(); } } }
好的程序员,他们删掉的代码,比留下来的还要多很多。