표현 트리의 빌드를 시도하는 두통, 특히 treenode 포인터를 구현하는 방법에 대한 단서가없고 실제적으로 있어야 할 데이터를 저장할 노드를 만드는 데 문제가 있습니다. 꽤 기본하지만 코드는 단지 나를 혼란스럽게합니다. 예를 들어표현 트리 구현 문제
, 내가 5이 그것을 어떻게 보일지입니다 + 5의 표현 만들려면 :이 구현 그러나 때
+
/\
5 5
을, 내가 시작하는 방법을 잘 모르겠어요. 루트 노드에서 연산자를, 자식 노드에서 숫자를 얻으려면 어떻게해야합니까? 나는 그 (것)들을 더미에서 저장할 수 있고 정상을 읽는다 그러나 벡터 토큰이 유형 끈 인 동안 세트 부모, 좌 아이 및 맞은 아이 방법은 (TreeNode *) 논쟁 만 가지고 간다.
또한 TreeNode의 생성자는 정수와 연산자 값을 사용합니다. 그 이유는 무엇입니까? 그 값들을 루트, 부모 및 자식으로 각각의 노드에 어떻게 가져올 수 있습니까?
ExprTree.cpp
#include "ExprTree.h"
#include <sstream>
#include <iostream>
TreeNode * createOperatorNode(const string & op){
if (op == "+") return new TreeNode(Plus);
if (op == "-") return new TreeNode(Minus);
if (op == "*") return new TreeNode(Times);
if (op == "/") return new TreeNode(Divide);
return new TreeNode(NoOp);
}
/*
* Basic constructor that sets up an empty Expr Tree.
*/
ExprTree::ExprTree(){
this->root = NULL;
this-> _size = 0;
}
/*
* Constructor that takes a TreeNode and sets up an ExprTree with that node at the root.
*/
ExprTree::ExprTree(TreeNode * r){
this->root = r;
}
ExprTree ExprTree::buildTree(vector<string> tokens){
// the tokens are the broken up arithimec expression
i.e
5
+
5
// not sure what to do here, i've tried using stacks but i wasn't sure how to get the stored data into the nodes.
}
는 TreeNode.cpp
#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;
}
TreeNode.h는
#include <string>
#include <sstream>
enum Operator {Value, Plus, Minus, Times, Divide, NoOp};
class TreeNode {
private:
Operator op; //If this node represents an operator, this is where it's stored.
//It can take values from the Operator enum (i.e. Plus, Minus, etc.)
//If it represents a value, use the Value value. :D
int value; //If this node stores an actual number, this is it.
TreeNode * parent; //Pointer to the parent.
TreeNode * leftChild; //Pointer to the left child of this node.
TreeNode * rightChild; //Pointer to the right child of this node.
public:
TreeNode(Operator); //Constructor to use for +, -, * and /.
//Example: TreeNode(Plus);
TreeNode(int); //Constructor to use for actual numbers.
//Example: TreeNode(5);
void setParent(TreeNode *); //Set the parent pointer.
void setLeftChild(TreeNode *); //Set the left child pointer.
void setRightChild(TreeNode *); //Set the right child pointer.
TreeNode * getParent(); //Get the parent pointer.
TreeNode * getLeftChild(); //Get the left child pointer.
TreeNode * getRightChild(); //Get the right child pointer.
int getValue(); //Returns the stored value;
Operator getOperator(); //Returns the stored operator.
bool isValue(); //Returns true if this node is a Value node.
bool isOperator(); //Returns truee if this node is Plus, Minus, Times or Divide node.
std::string toString(); //Returns a simple string representation of the node.
};
'ExprTree.h'는 어디에 있나요? –