abc-cba
abc-cba

Reputation: 13

C++ Binary Tree Traversal Inorder, Preorder and Postorder

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?

Upvotes: 0

Views: 1558

Answers (1)

user4581301
user4581301

Reputation: 33932

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.

Upvotes: 1

Related Questions