Skip to main content
1 of 3
Loki Astari
  • 96.6k
  • 5
  • 125
  • 338

In int bt_depth(struct BTnode * tree)

Too many different checks for NULL.
You only need to check once. The call to bt_depth() on the left and right nodes will perform there own explicit checks don't try and pre optimize.

int bt_depth(struct BTnode * tree)
{
  if( tree == NULL ) return 0;
  int leftdepth  = bt_depth(tree->left);
  int rightdepth = bt_depth(tree->right);

  return max(leftdepth, rightdepth) + 1;
}

In int bt_encode_preorder(int * list, struct BTnode * tree, int index)

You are using tree without check for NULL tree

list[ index++ ] = tree->data;

You are also doing a recursive call without checking.
At some point you may end up hitting a NULL and trying to de-reference it.

if( tree->left != NULL )
{
  index = bt_encode_preorder(list, tree->left, index);
  index = bt_encode_preorder(list, tree->right, index); // tree->right may be NULL!!!!
}
Loki Astari
  • 96.6k
  • 5
  • 125
  • 338