Your first problem case is when you find a leaf: all your closing brackets ()
) are doubled, because you try to advance toward the left and right links, but you find null
s, which trigger the ending bracket in your code.
private void serializePrefix (Node t, StringBuilder str, String sep){
int ID = 1;
if (t == null)
//ERROR: if empty node found, apply close bracket
str.append(")");
else{
str.append("(" + t.data.toString() );
str.append(sep);
//this is the problem part, for example for node number 1:
serializePrefix (t.left, str, sep); //this writes ")" first time
serializePrefix (t.right, str, sep); //this writes ")" second time
}
ID++;
}
The second issue is, that on the last branch, your brackets would not get closed properly, because when your algorithm "steps back" to the root, it does not close the opened brackets as it steps back one by one...
Fix proposal:
private void serializePrefix (Node t, StringBuilder str, String sep){
int ID = 1;
if (t == null)
// do nothing!
// str.append(")");
else{
str.append("(" + t.data.toString() );
str.append(sep);
//this is the problem part, for example for node number 1:
serializePrefix (t.left, str, sep); //this writes ")" first time
serializePrefix (t.right, str, sep); //this writes ")" second time
//close opened bracket
str.append(")");
}
ID++;
}
(by the way, it is a general advice to try to close what you open in the visible distance from where you opened it... This helps a lot with controlling leaks around resources like DB connections and the likes.)