表达式树 [英] expression Tree
本文介绍了表达式树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个表达式树和遍历遍历,但这是行不通的.问题可能与指针(* left和* right)有关,但我没有发现任何错误.代码在这里;
I wrote a expression tree and preorder traversal , but this doesn''t work. The problem is probably related to pointers(*left and *right) But I haven''t found anything wrong. Code is here;
#include <iostream>
#include <string>
#include <vector>
#include "Node.h"
using namespace std;
void preorderTraversal(Node *root){
if(root != NULL){
cout << root->c;
preorderTraversal(root->left);
preorderTraversal(root->right);
}
}
int main() {
string s = "ab+cde+**";
vector<Node> lst;
Node *left ;
Node *right ;
for(int i = 0; i < s.size(); i++){
bool b =((s[i]=='*') || (s[i]=='+') || (s[i]=='-') || (s[i]=='\\') || (s[i]=='^'));
if(b){
left = new Node();
right = new Node();
*right = lst.at(lst.size()-1);
lst.pop_back();
*left = lst.at(lst.size()-1);
lst.pop_back();
lst.push_back(Node(s[i],left,right));
delete left;
delete right;
left = NULL;
right = NULL;
}else{
lst.push_back(Node(s[i]));
}
}
cout << lst.size()<<endl;
preorderTraversal(&lst.back());
return 0;
}
#define NODE_H_
using namespace std;
#include <iostream>
class Node {
public:
Node();
Node(char c, Node *left, Node *right);
Node(char c);
~Node();
char c;
Node *left;
Node *right;
private:
};
#endif /* NODE_H_ */
#include "Node.h"
Node::Node() {
// TODO Auto-generated constructor stub
this->c = NULL;
left = NULL;
right = NULL;
}
Node::Node(char c){
this->c = c;
left = NULL;
right = NULL;
}
Node::Node(char c, Node *left, Node *right){
this->c = c;
this->left = left;
this->right = right;
}
Node::~Node() {
// TODO Auto-generated destructor stub
}
如果有人可以提供帮助,我将非常感激.
If anyone can help with this I would really appreciate it.
推荐答案
您确定要执行此操作吗?
Are you sure you want to do this?
delete left;
delete right;
left = NULL;
right = NULL;
我可能不明白您要在这里做什么,但是看起来您存储了一堆原始指针,然后删除了它们指向的对象.我会重写Node
来执行所有内存管理,并将其保留在main之外.
干杯,
Ash
I may not understand what you''re trying to do here but it looks like you store a bunch of raw pointers then delete the objects they''re pointing to. I''d rewrite Node
to do all the memory management and keep it out of main.
Cheers,
Ash
我想在if块中每次都在delete
左右移动,因为我认为当new
分配Node时,这堆指针可能会不必要地消耗内存.所以我以为我可以通过删除指针来保护这种消耗.我不知道很好地使用指针.这是我的想法(但这可能是错误的.我不明白这是怎么回事).
但是,当我删除此部分并尝试在for循环之后左右写delete时,它可以正常工作.
如何在Node中处理内存管理?
感谢您的帮助.
I wanted todelete
left and right for every time in if block because I thought when a Node is allocated bynew
, this bunch of pointers may consume unnecessarily memory. So I thought I protected this consumption by deleting pointer. I don''t know to use pointers very well. This is my thought (But this is probably wrong. I don''t understand what is wrong with that).
But when I remove this part and try to write delete left and right after for loop, it works fine.
How can I handle memory management in Node?
Thanks for help.
这篇关于表达式树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文