Build expression tree based on suffix expression java

concept

The tree used to express the expression is called the expression tree. In the expression tree, the leaf nodes are operands, and the non-leaf nodes are operators. That is to say, the expression tree is an internal node as an operator, and the leaf node is The binary tree of the manipulation tree,

Insert picture description here

Code

BinaryTreeNode buildExprTree(char postFixExpr[],int size){
    
    
  LLStack s = new llStack();
  for(int i = 0;i<size;i++){
    
    
    if(isOperand(postFixExpr[i])){
    
    
      BinaryTreeNode node = new BinaryTreeNode();
      if(node == null){
    
    
        System.out.println("Out of memory!");
        return null;
      }
      node.setData(postFixExpr[i]);
      node.setLeft(null);
      node.setRight(null);
      s.push(node);
    }
    else{
    
    
      BinaryTreeNode t2 = s.pop();
      BinaryTreeNode t1 = s.pop();
      BinaryTreeNode newNode = new BinaryTreeNode();
      if(newNode == null){
    
    
        System.out.println("Out of memory!");
      }
      newNode.setData(postFixExpr[i]);
      newNode.setLeft(t1);
      newNode.setRight(t2);
      s.push(newNode);
    }
  }

}

boolean isOperand(char c){
    
    
  if(c == '+' || c== '-' || c=='*' || c=='/'){
    
    
    return false;
  }
  return true;
}

Guess you like

Origin blog.csdn.net/weixin_37632716/article/details/115186888