我做的這個問題: https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/在C++中實現這種工作流程的最佳方法是什麼?
我的方法是序列化的字符串分配給像 「1#,2#,#」 流。 然後從流中讀取一個字符。如果它是'#',則返回。否則, 訪問左側和右側的孩子。
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,#,#");
}
早些時候,我被檢查
if (!pre.str().size())
,因爲我錯誤地預計流刪除所提取的字符。現在我維護着char_count,但代碼不再優雅。有什麼方法可以在C++中簡化這個。
你想做什麼? – sharyex
在我從流中提取1個字符後,它不應該是33。 –
'stringbuf :: str()'返回整個基礎緩衝區。嘗試做'q_s.str()。substr(q_s.tellg())' – 0x499602D2