Segmentation fault error


please check
the horizontal distance of node 6 is being calculated wrong in my code it is -3but it should not be that

That’s because of multiple error, in while condition line 45 instead of queue.size use !queue.empty()
Do one thing take reference from this code


It might help you :slight_smile:


resolved the segmentation fault error but getting wrong output

The logic you have used will not give the desired output, you can dry run it also.

where it is wrong
image
for 3 and 1 horizontal distance is right
but for 6 only it is wrong

check for this case->
1 6 2 8 7 4 3 11 -1 9 -1 -1 5 -1 -1 -1 -1 10 -1 -1 -1 -1 -1

expected ->
11 8 6 1 2 3

And you can’t use any extra data member like you have declared it in class node. First correct your this concept then try it without using horizontal distance data member.

i found this solution on gfg and implemmented it

Have you submitted your code ?

Oh I got it why you are failing it. In GeeksforGeeks editorial they are building tree in a level order manner and you are doing it recursively. See this you will get to know.

so what i need to change

Instead of building your binary tree recursively, build it in a level order . But keep this in mind the inputs are given for recursive building of a tree.
Or you can prefer the code i have given you above. It’s upto you :slight_smile:

both codes are very similar which function of my code is causing problems
is it the build tree fuction?

Yes @kartik-malik it’s the build tree function

Moreover, your build tree function is absolutely fine for building tree recursively. But the logic you have used is not for recursive building of tree. It’s for level order building of tree.

what is the difference between both i take root then its child then childs of each node

When we recursively build tree it can be in prefix postfix and infix too.
But the editorial you have shared with me has build tree using level order.

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.