C++ using counter


  • 1
    A
    class Solution {
    public:
        bool isValidSerialization(string preorder) {
            replace(preorder.begin(),preorder.end(),',',' ');
            stringstream ss(preorder);
            string value;
            int nbTreeToRead = 1;
            while(ss >> value)
            {
                if (nbTreeToRead == 0) return false;
                if (value == "#") nbTreeToRead --;
                else nbTreeToRead++;
            }
            return (nbTreeToRead == 0);
        }
    };

  • 0
    I

    Why do you decrement nbTreeToRead when the character read is a #?


  • 0
    A

    nbTreeToRead represent the number of trees we need to read.

    There are to types of tree.
    -> leaf
    -> Tree that are made of two sub treee

    if we reach a leaf, we have read 1 tree. (So nbTreeToRead --)
    else we have also read 1 tree, but we need to read 2 subtrees (so nbTreeToRead += 2 - 1;)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.