如何使用矢量字符串标记构建表达式树?

时间:2017-04-23 07:35:59

标签: c++ algorithm data-structures expression binary-tree

我几个小时以来一直在讨论这个问题,而且似乎无法找到完成它的方法。基本上我试图插入一个破碎的算术字符串表达式,例如。 " 12" " *" " 15"到二进制表达式treeNodes。

#include "TreeNode.h"

TreeNode::TreeNode(Operator o){
  op = o;
  parent = 0;
  leftChild = 0;
  rightChild = 0;
}

TreeNode::TreeNode(int val){
  op = Value;
  value = val;
  parent = 0;
  leftChild = 0;
  rightChild = 0;
}

void TreeNode::setParent(TreeNode * p){ parent = p; }

void TreeNode::setLeftChild(TreeNode * l){

  if (op != Value){
    leftChild = l;
  }

}

void TreeNode::setRightChild(TreeNode * r){

  if (op != Value){
    rightChild = r;
  }

}

TreeNode * TreeNode::getParent(){ return parent; }

TreeNode * TreeNode::getLeftChild(){ return leftChild; }

TreeNode * TreeNode::getRightChild(){ return rightChild; }

int TreeNode::getValue(){ return value; }

Operator TreeNode::getOperator(){ return op; }

bool TreeNode::isValue(){ return op == Value; }

bool TreeNode::isOperator(){ return op != Value && op != NoOp; }

std::string TreeNode::toString(){

  if (isValue()){

    std::stringstream stream;
    stream << getValue();
    return stream.str();

  }

  switch (op){

  case Value : return "val";
  case Plus : return "+";
  case Minus : return "-";
  case Times : return "*";
  case Divide : return "/";
  case NoOp : return "";
  }

}

ExprTree.cpp

/*
 * Basic constructor that sets up an empty Expr Tree.
 */
ExprTree::ExprTree(){


}

/*
 * Constructor that takes a TreeNode and sets up an ExprTree with that node at the root.
 */
ExprTree::ExprTree(TreeNode * r){

    this->root = r;
}

/*
 * Destructor to clean up the tree.
 */
ExprTree::~ExprTree(){


}

/*
 * This function takes a vector of strings representing an expression (as produced
 * by tokenise(string), and builds an ExprTree representing the same expression.
 */
ExprTree ExprTree::buildTree(vector<string> tokens){

         //function in question
    }

向量包含一个拆分算术表达式(我没有添加函数,因为它有点长),这意味着要存储在树节点中以创建表达式树,其中运算符( +, - ,*)是父节点或根节点,数字是叶子。问题是能够分离数字并将它们插入左右叶子中,迭代不允许我使用for循环来执行此操作。

1 个答案:

答案 0 :(得分:1)

您正在寻找的内容称为“解析器”,它将获取令牌流并输出AST。这是编译器构建中的一个巨大领域,有许多不同的方法。

Dragon Book(很容易在网上找到PDF版本)是我学到很多理论的方法,我仍然强烈推荐它作为这个主题的一个很好的介绍。

在线进行研究,从Wikipedia开始,了解一般方法和不同方法。然后,您可以更专门地针对您认为可能适合的某些类型的解析器进行谷歌搜索。

对于简单的表达式,shift-reduce解析器很常见,但我的goto选项是Pratt的Top Down Operator Precedence Parser,我发现它是一种非常简洁的方法(this是一个很好的解释)。