【发布时间】:2018-09-09 02:50:12
【问题描述】:
我目前正在处理一个 C++ 项目,其中一部分是使用中序、前序和后序遍历二叉树。
class TNode
{
public:
int val;
TNode() {}
TNode(int v) { val = v; }
TNode * left;
TNode * right;
TNode * parent;
};
class BTree
{
void print_pre_order(TNode *r);// print the node as you traverse according to the order.
void print_in_order();
void print_post_order();
}
BTree::BTree()
{
root = new TNode(1);
root->parent = 0;
root->left = new TNode(2);
root->right = new TNode(3);
root->left->left = new TNode(4);
root->left->right = new TNode (5);
root->right->left = new TNode(6);
}
void BTree::print_pre_order(TNode *r)
{
if (r == 0)
{
return;
}
cout << r->val;
print_pre_order(r->left);
print_pre_order(r->right);
}
int main()
{
BTree y;
y.print_pre_order(y.root);
return 0;
}
在我的默认构造函数中,我已经初始化了一些节点的值,但是当我运行代码时,我得到的输出是“124”并出现错误。我不知道我哪里做错了,有人可以帮忙吗?
【问题讨论】:
-
定义 BTree 成员变量 root 并在 BTree() 构造函数中初始化,在遍历之前用节点填充 Btree。程序非常不完整。
-
错误是什么?
-
由于我使用的是 Visual Studio,它只显示“程序已停止工作”@smac89
-
你能走到这一步真是太棒了。
class BTree似乎没有BTree::BTree()或任何使用的成员变量。 -
编辑您的问题以包含minimal reproducible example。
标签: c++ binary-tree tree-traversal inorder preorder