Recursively collapse each leaf node (replace "n,#,#" with "#") to check you left with "#" at the end

```
public boolean isValidSerialization(String s) {
if(s.equals("#")) return true;
if(s.length()<5 ) return false;
int before=0, after=0;
do{
before = s.length();
s=s.replaceAll("\\d+,#,#", "#");
after = s.length();
}while(before!=after);
return s.length()==1;
}
```