Reputation: 115
I am doing this problem: https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/
My approach is to assign serialized string to a stream like "1,#,2,#,#". And then read a character from stream. If it is a '#', return. Else, visit left and right child.
class Solution {
stringstream pre; int char_count = 0;
public:
bool visit() {
if (char_count >= pre.str().size()) return 0;
char key; char comma;
while (char_count < pre.str().size() && pre.peek() != ',') {
pre >> key;
char_count++;
}
if (pre.peek() == ',') {
pre >> comma;
char_count++;
}
if (key == '#') return 1;
return visit() && visit();
}
bool isValidSerialization(string preorder) {
pre << preorder;
cout << "preorder: " << preorder << endl;
if (!visit()) return 0;
if (pre.str().size() > char_count) return 0;
return 1;
}
};
int main() {
Solution q;
cout << q.isValidSerialization("1,#,#");
}
Earlier, I was checking for
if (!pre.str().size())
because I wrongly expected stream to delete the extracted characters. Now I am maintaining char_count but the code is no longer elegant. Is there any way to simplify this in C++.
Upvotes: 0
Views: 67
Reputation: 33864
Have a look here. There is no overload for the operator>>(char)
, it is likely being implicitly cast to something else. This is the expected behaviour of the code you have written.
Upvotes: 1