1

I am confused by the following codes and try to understand what they mean.

 if( (root->left == NULL) || (root->right == NULL) )
 {
    Node *temp = root->left ? root->left : root->right;
 }

it means if root->left ==NULL then temp = root->left? else temp = root->right?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user3369592
  • 1,367
  • 5
  • 21
  • 43

3 Answers3

5

You are not exactly right, but u get the idea. This is a conditional operator which takes three operands.

 var = condition ? expression1 : expression2

is equivalent to

if( condition )
  var = expression1
else
  var = expression2

In your case it means

if root->left != NULL then temp = root->left, else temp = root->right

instead of

if root->left ==NULL then temp = root->left, else temp = root->right

Rakib
  • 7,435
  • 7
  • 29
  • 45
  • The part of the question beginning with "it means..." is wrong (the condition should read `!= NULL`), so saying "you are right" is not correct. – DCoder Jun 19 '14 at 05:47
  • 1
    Also, the operator's real name is the *conditional operator*, as in OP's question (see **5.16 Conditional operator [expr.cond]**.) – juanchopanza Jun 19 '14 at 06:01
  • @DCoder, thanks for correcting me. I overlooked it the `==`operator. – Rakib Jun 19 '14 at 06:08
  • The ternary operator `?:` returns a value whereas the `if` statement does not. – Tobias Jun 19 '14 at 06:13
1

It means the following: If left and right are NULL, then temp equals NULL, otherwise if left is NULL, then temp equals right, otherwise if right is NULL, then temp equals left.

ThomasMcLeod
  • 7,603
  • 4
  • 42
  • 80
1

You're wrong. It means if root->left == NULL then *temp = root->right,
else if root->right == NULL then *temp = root->left,
else *temp will not be set.

There're 4 possible cases:

  1. root->left == NULL and root->right != NULL, *temp will be root->right.
  2. root->left == NULL and root->right == NULL, *temp will be root->right.
  3. root->left != NULL and root->right != NULL, *temp will not be set.
  4. root->left != NULL and root->right == NULL, *temp will be root->left.

Now you can see that 2nd and 3rd case may be potential problem.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405