【问题标题】:How to build an expression tree with vector string tokens?如何使用向量字符串标记构建表达式树?
【发布时间】:2017-09-19 23:35:51
【问题描述】:

我已经为这个问题绞尽脑汁好几个小时了,但似乎找不到解决方法。基本上我正在尝试插入一个分解的算术字符串表达式,例如。将“12”“*”“15”转化为二叉树节点。

#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 循环。

【问题讨论】:

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


【解决方案1】:

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

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

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

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

【讨论】:

  • 如果 this 也是你(看起来很可能),那么在那里研究整个编译器构造,因为该主题也被广泛涵盖。
猜你喜欢
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-02
  • 1970-01-01
相关资源
最近更新 更多