C 二进制树横穿有序,预订和邮政

C++ Binary Tree Traversal Inorder, Preorder and Postorder

本文关键字:二进制      更新时间:2023-10-16

我目前正在从事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",并且会出现错误。我不知道我在哪里做错了,有人可以帮忙吗?

我看到该程序曾经将任何指针设置为零的迹象,因此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;
};

:告诉编译器成员初始化器列表即将到来。之后,代码初始化所有指向NULL的指针成员。

更改

if (r == 0)

to

if (r == nullptr)

更好地传达意图,您应该很好。