【发布时间】: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 循环。
【问题讨论】:
-
阅读后缀符号。 cs.csi.cuny.edu/~zelikovi/csc326/data/assignment5.htm 也可以读中缀到后缀。从使用堆栈的后缀中,您可以轻松创建 exp 树
标签: c++ algorithm data-structures expression binary-tree