This is my second approach for this question.
Firstly it is not mentioned in the question that ’ -1 ’ will represent null for that specific node.
This time I considered it to represent null.
Please have a look at my code .
Is my construction for the tree is correct ?
Wrong Answer Error
@mananaroramail,
https://ide.codingblocks.com/s/166874 Here is the corrected code. Note: I used global scanner.
Errors:
- Fill Public node constructor
- Initialize private Node root as null and size as 0.
- Directly pass the data onto the node as constructor will assign it.
- You need to use Queue instead of LinkedList.
- MOST IMPORTANT: Since you are not using buffer reader incase the queue isn’t empty and the input string is finished. It will throw a run time error. For that use .hasNextInt() to check. If the next input is not an int, it will break and return the root node as it would mean the input is over.
- While printing right view nodes use a queue instead of recursion method
Is it not " null " for Node and " 0 " by default ?
Also if the tree is like :
1
/ \
2 3
/ \
4 5 6
Then the answer should be " 1 3 " or " 1 3 6 " ?
I used Linked List as a queue
Why was recursion a problem ?
The queue approach is quite analytical !!
I tried it that way as well but I still faced errors.
This was the code : https://ide.codingblocks.com/s/164556
As it was not mentioned in the question that " -1 " represents null so I took it as a part of the tree.
- Is int size and int size=0 the same? I hope you got the answer
- to which node is 6 connected to?
- Line 35 of your original code you were creating an object “queue” of the LinkedList class. You weren’t creating an object of the Queue class.
- Recursion was not a problem, its just that if you use a queue its better to understand the flow. You can implement the same using recursion not a problem.
- You have only implemented the bufferedreader in place of scanner. But rest of the errors remain. The constructor is incomplete too.
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.