These functions will give the same output, and they are both correct, but I want to know which is programmatically more appropriate?
code 1:
void inorder(node *t){
if(t==NULL)
return;
else{
inorder(t->left);
cout<<t->data<<" ";
inorder(t->right);
return;
}
}
code 2:
void inorder(node *t){
if(t){
inorder(t->left);
cout<<t->data<<" ";
inorder(t->right);
}
}
Here node is a node of binary tree, having the structure:
struct node{
int data;
node *left;
node *right;
};
The second one looks better.
However, I'd personally prefer this:
It is explicit (that you dont intend to do anything if
tis NULL) and avoids unnecessary block (and thus indentation) by removing the else. This approach also increases the readability and makes the code concise (think of bigger function and/or blocks, and removing of unnecessary elses).I might refactor this function, making it two as:
This way you can even print the tree to a file if you use the first function, as:
Hope that helps.