Ok, I have recently started attempting tree related problems, there is a simple code that finds the Height of a binary search tree. It works fine on my system on CodeBlocks, but gives different output (2 every time) when I compile it on online IDEs.
For example
On codeblocks
4
2 1 3 4
gives output 3
but on online IDEs
4
2 1 3 4
gives output 2
not only this test case, but all test cases give output 2 online. Please Help!!
the code: https://ideone.com/rm5vIa
Can you elaborate on the input format please?
Hey @merajeev
Your height function is correct, the problem lies in the creation of tree. Your code always creates tree with a root and its two children. The tree does not contain any other element than these three. I just called the preorder before calculating the height and it showed me only three elements. Here is the code for that.
Try debugging it as to why your tree is not getting created properly. But if you still don’t get the mistake, you can check the hidden text.
Click to view
You are not returning any node from the insert function. That is the reason why your tree is not getting updated properly. Just add return node; at the end of insert function and the code works fine.
Yes, We have to manually revisit the nodes. Although recursion would have done that but if we do not return anything then garbage value will be assign to nodes (left and right child).
This code may not run in Java because there are situations when fun will not be returning anything but we are storing it in node->left or node->right.
In c++ some garbage is getting returned. So a return node will take care of everything. This code (without return )runs on Sublime , Codeblocks. Strange!
Hope this make sense. Please correct if wrong.