【发布时间】:2012-10-07 05:01:04
【问题描述】:
我所做的如下,但是我在破坏树和尝试打印树时遇到了很多问题(基本上我需要在树上使用递归的任何地方)。
这是因为在尝试在右子树的左侧递归调用 print 时,我的方法中断了,因为我的左右子树实际上只有 Nodes 而不是 Trees。因此,我需要将我的节点类型化为 Trees,或者我需要创建新的树,这两者都是丑陋的解决方案。
我认为这里的问题在于类设计。你能评论一下吗?谢谢!
class Node {
int _data;
public:
Node* left; // left child
Node* right; // right child
Node* p; // parent
Node(int data) {
_data = data;
left = NULL;
right = NULL;
p = NULL;
}
~Node() {
}
int d() {
return _data;
}
void print() {
std::cout << _data << std::endl;
}
};
class Tree {
Node* root;
public:
Tree() {
root = NULL;
}
Tree(Node* node) {
root = node;
}
~Tree() {
delete root->left; // this is NOT RIGHT as
// it only deletes the node
// and not the whole left subtree
delete root->right;
delete root;
}
void print(int);
void add(int);
};
【问题讨论】:
-
Node *p应该是什么?一个节点只有左右孩子... -
什么是 Node::p?编辑:该死的 nneonneo:P
-
p 是父指针。
-
啊。说得通。 (可能应该称为
*parent)。 -
查看this implementation,我觉得设计不错。那里缺少析构函数,您只需要按照 Rollie 在他的回答中指出的方式进行即可
标签: c++ data-structures tree