package ExpressionTree; import TraverseTree.TNode; import java.util.Stack;; /** * 表达式树 */ public class ExpTree { /**表达式树的构建*/ public static TNode<Character> buildExpTree(String postfixExp) { char c; TNode<Character> newNode, newLeft, newRight; Stack<TNode<Character>> s = new Stack<TNode<Character>>(); int i = 0, len = postfixExp.length(); while(i != len) { while(postfixExp.charAt(i) == ' ' || postfixExp.charAt(i) == '\t') i++; if(i == len) break; c = postfixExp.charAt(i); i++; if(c == '+' || c == '-' || c == '*' || c == '/') { newRight = s.pop(); newLeft = s.pop(); newNode = new TNode<Character>(c, newLeft, newRight); s.push(newNode); } else { newNode = new TNode<Character>(c); s.push(newNode); } } if(! s.isEmpty()) return s.pop(); else return null; } /**中序输出*/ public static <T> void inorderOutput(TNode<T> t) { if (t != null) { inorderOutput(t.left); System.out.print(t.nodeValue + " "); inorderOutput(t.right); } } public static void main(String[] args) { String exp = "abc*+"; TNode<Character> root = ExpTree.buildExpTree(exp); ExpTree.inorderOutput(root); // a + b * c } }