Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
810 views
in Technique[技术] by (71.8m points)

algorithm - Build Binary Expression Tree

Could someone explain how to build a binary expression tree.

For example I have a string 2*(1+(2*1)); How to convert this into a binary expression tree.

 *
 | 
 |  
 2  +
    |
    1 *
      |
      2 1
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Convert infix to postfix or prefix

The postfix input is: a b + c d e +**

  1. Consider first character if it is not symbol then create node add it to stack
  2. If character is symbol then create node with symbol pop elements and add to left and right of symbol
  3. Push symbol node in to the stack.
  4. Repeat 1, 2 and 3 till iterator has no more elements

Java Implementation

public Tree.TreeNode createExpressionTree(){
    Iterator<Character>itr = postOrder.iterator();
    Tree tree = new Tree();
    NodeStack nodeStack = new NodeStack();
    Tree.TreeNode node;
    while (itr.hasNext()) {
        Character c = itr.next();
        if(!isDigit(c)){
            node = tree.createNode(c);
            node.right = nodeStack.pop();
            node.left = nodeStack.pop();
            nodeStack.push(node);
        }else{
            node = tree.creteNode(c);
            nodeStack.push(node);
        }
    }
    node = nodeStack.pop();
    return node;
}

More info: http://en.wikipedia.org/wiki/Binary_expression_tree


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...