构建表达式树

来源:互联网 发布:友邦高端医疗险 知乎 编辑:程序博客网 时间:2024/05/16 18:20
public static TNode<Character> buildExpTree(String postfixExp){AStack<TNode<Character>> stack=new AStack<TNode<Character>>();TNode<Character> newNode,newLeft,newRight;char token;int i=0;int n=postfixExp.length();while(i<n){while(postfixExp.charAt(i)==' '||postfixExp.charAt(i)=='\t')i++;if(i==n)break;token=postfixExp.charAt(i);i++;if(token=='+'||token=='-'||token=='*'||token=='/'){newRight=stack.pop();newLeft=stack.pop();newNode=new TNode<Character>(token,newLeft,newRight);stack.push(newNode);}else{newNode=new TNode<Character>(token);stack.push(newNode);}}if(!stack.isEmpty()){return stack.pop();}elsereturn null;}

原创粉丝点击