Skip to content

Latest commit

 

History

History
40 lines (36 loc) · 861 Bytes

331. Verify Preorder Serialization of a Binary Tree.md

File metadata and controls

40 lines (36 loc) · 861 Bytes
class Solution {
public:
    bool isValidSerialization(string preorder) {
        istringstream iss(preorder);
        vector<string> arr;
        string s;
        int cnt = 0;
        while (getline(iss, s, ',')) arr.push_back(s);
        for (int i = 0; i < arr.size() - 1; ++i) {
            if (arr[i] == "#") {
                if (cnt == 0) return false;
                cnt--;
            } else {
                cnt++;
            }
        }
        return cnt == 0 && arr.back() == "#";
    }
};
class Solution {
public:
    bool isValidSerialization(string pre) {
        int cnt = 1;
        pre += ",";
        for (int i = 0; i < pre.size(); ++i) {
            if (pre[i] != ',') continue;
            if (--cnt < 0) return false;
            if (pre[i - 1] != '#') cnt += 2;
        }
        return cnt == 0;
    }
};