【问题标题】:C++ Binary Tree Traversal Inorder, Preorder and PostorderC++二叉树遍历中序、前序和后序
【发布时间】: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


【解决方案1】:

我没有看到程序将任何指针设置为零的迹象,因此if (r == 0) 不太可能触发退出。

试试这个:

class TNode
{
  public:
  int val;
  TNode(): val(0), left(nullptr), right(nullptr), parent(nullptr) {}
  TNode(int v): val(v), left(nullptr), right(nullptr), parent(nullptr) {}
  TNode * left;
  TNode * right;
  TNode * parent;
};

: 告诉编译器 member initializer list 即将到来。之后,代码将所有指针成员初始化为指向 null。

改变

if (r == 0)

if (r == nullptr)

为了更好地传达意图,你应该很高兴。

【讨论】:

  • 非常感谢您的帮助!代码正在运行!再次感谢。 @user4581301
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-08
  • 1970-01-01
  • 2023-01-09
  • 1970-01-01
  • 2021-09-03
  • 1970-01-01
相关资源
最近更新 更多