331. 验证二叉树的前序序列化

 1 //空节点的个数 = 非空节点个数 + 1
 2 class Solution 
 3 {
 4     vector<string> res; 
 5     void spilt(string s,char c)
 6     {
 7         istringstream iss(s);
 8         string temp;
 9         while(getline(iss,temp,c))
10         {
11             //如果temp不为空,才可以添加进去
12             if(!temp.empty()) res.push_back(temp);
13         }
14     }
15 public:
16     bool isValidSerialization(string preorder) 
17     {
18         spilt(preorder,',');
19         int a = 0;//空节点的个数
20         int b = 0;//非空节点的个数
21         for(auto r : res)
22         {
23             if(a > b) return false;//1、当前的空节点数不能大于非空节点数
24             if(r == "#") a ++;
25             else b ++;
26         }
27         return a == b + 1;//2、空节点的个数 = 非空节点个数 + 1
28     }
29 };

 

posted @ 2020-04-21 22:21  Jinxiaobo0509  阅读(167)  评论(0)    收藏  举报