Just string problem 8 lines and 4 ms .this C++ code is very easy to understand.


  • 2
    2
    class Solution {
    public:
    	bool isValidSerialization(string preorder) {
    		int i, nul = 0, node = 1;
    		for (i = 0; i < preorder.length(); ++i){
    			if (preorder[i] == ',')node++;
    			if (preorder[i] == '#')nul++;
    			if (2 * nul == node + 1 && i != preorder.length() - 1)return false;
    		}
    		return 2 * nul == node + 1;
    	}
    };

  • 0

    What does the 2*nul == node + 1 mean? What about this 1,1,#,#,# ?
    At last, node = 6, nul = 3. Ah yes, the number of leaves times two should be the number of nodes plus one.


Log in to reply
 

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