Unexpected result regarding comparing two pointer-related integer values in C++

I have a BST of three elements {1, 2, 3}. Its structure looks like

1
2
3
  2
 / \
1   3

Now I try to calculate the height for each node using BSTHeight() defined below and have some problem with calculating the height of '2', which value is supposed to be 1 as the heights of '1' and '3' are defined as 0. My problem is that with direct use of heights from '2's two children (see part 2 highlighted below), its height is ALWAYS 0. However, its value is correct if I use two temporary integer variables (see part 1 highlighted below). I couldn't see any difference between the two approaches in terms of functionality. Can anyone help explain why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
void BSTHeight(bst_node *p_node)
{
    if (!p_node) 
        return;

    if (!p_node->p_lchild && !p_node->p_rchild) {
        p_node->height = 0;
    } else if (p_node->p_lchild && p_node->p_rchild) {
        BSTHeight(p_node->p_lchild);
        BSTHeight(p_node->p_rchild);
#if 0   // part 1
        int lchild_height = p_node->p_lchild->height;
        int rchild_height = p_node->p_rchild->height;
        p_node->height = 1 + ((lchild_height > rchild_height) ? lchild_height : rchild_height);
#else   // part 2
        p_node->height = 1 + ((p_node->p_lchild->height) > (p_node->p_rchild->height)) ? (p_node->p_lchild->height) : (p_node->p_rchild->height);
#endif
    } else if (!p_node->p_lchild) {
        BSTHeight(p_node->p_rchild);
        p_node->height = 1 + p_node->p_rchild->height;
    } else {
        BSTHeight(p_node->p_lchild);
        p_node->height = 1 + p_node->p_lchild->height;
    }
}
Change the statement

p_node->height = 1 + ((p_node->p_lchild->height) > (p_node->p_rchild->height)) ? (p_node->p_lchild->height) : (p_node->p_rchild->height);

to

p_node->height = 1 + ( ((p_node->p_lchild->height) > (p_node->p_rchild->height)) ? (p_node->p_lchild->height) : (p_node->p_rchild->height) );

that is enclose the conditional operator in parentheses.

EDIT: you placed too many parentheses that it is difficult to read this statement. Remove unnecessary parentheses.

p_node->height = 1 + ( p_node->p_lchild->height > p_node->p_rchild->height ? p_node->p_lchild->height : p_node->p_rchild->height );
Last edited on
Thanks a lot, Moscow. it works.

So it means operator '+' has higher priority than '?' and it is necessary to use a pair of '()' to surround the code 'a>b?a:b', isn't it?

Many thanks again.
Topic archived. No new replies allowed.