程式語言 - LeetCode - C++ - 331. Verify Preorder Serialization of a Binary Tree



題目:


解答:

class Solution {
public:
    bool isValidSerialization(string preorder) {
        int slot = 1;
        string token;
        stringstream ss(preorder);

        while (getline(ss, token, ',')) {
            slot -= 1;

            if (slot < 0) {
                return false;
            }

            if (token != "#") {
                slot += 2;
            }
        }

        return slot == 0;
    }
};