0

I'm currently working on a C++ project and part of it is to traverse the binary tree using inorder, preorder, and postorder.

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;
}

In my default constructor, I've initialized values for some nodes, but when I run the code, the output I'm getting is "124" and gets an error. I don't know where I did wrong, can someone help?

8
  • Define BTree member variable root and initialize in BTree() contructor, populate Btree with nodes before traversal. Program is very incomplete.
    – seccpur
    Mar 30, 2018 at 3:43
  • What is the error?
    – smac89
    Mar 30, 2018 at 3:46
  • Since I'm using Visual Studio, it only says "the program has stoped working" @smac89
    – abc-cba
    Mar 30, 2018 at 3:52
  • 1
    Amazing you got that far. class BTree doesn't seem to have a BTree::BTree() or any of the used member variables. Mar 30, 2018 at 3:53
  • 1
    Edit your question to include a minimal reproducible example.
    – Sid S
    Mar 30, 2018 at 3:56

1 Answer 1

1

I see no signs that the program ever sets any any pointers to zero, so if (r == 0) is unlikely to ever trigger an exit.

Give this a try:

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;
};

The : tells the compiler that a member initializer list is coming. After that the code initializes all of the pointer members to point at null.

Change the

if (r == 0)

to

if (r == nullptr)

to better convey intent and you should be good to go.

1
  • I really appreciate your help! The code is working ! Thanks again. @user4581301
    – abc-cba
    Mar 30, 2018 at 4:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.