331. Verify Preorder Serialization of a Binary Tree
仅供自己学习
思路:
看的题解知道了新的思维,就是槽位。对于此题来说相当于preorder中每个元素除了‘,’外,都占用一个槽位,对于’#‘来说,只消耗1个槽位但不产生槽位,而数字元素消耗1个槽位并且产生两个孩子槽位。因为只是检验是否是正确的二叉树前序遍历,所以只要满足遍历preorder的时候 栈不空,遍历完后栈空,那么就满足是二叉树,因为我们产生槽位都是按照二叉树来产生,所以我们也只需要判断槽位是否能用完即可不需要判断顺序是否正确,那么每加入一个数字,应该会马上填满他的槽位,并生成新的槽位。当槽位用完的时候我们要立马把他删掉,如果是数字就删掉后再添加新的槽位。
一开始我们将一个槽位先加入栈中用作源节点的槽位。
代码:
1 class Solution { 2 public: 3 bool isValidSerialization(string preorder) { 4 int size=preorder.length(); 5 stack<int> st; 6 st.push(1); 7 int i=0; 8 while(i<size){ 9 if(st.empty()) return false; 10 if(preorder[i]==',') i++; 11 else if(preorder[i]=='#'){ 12 st.top()-=1; 13 if(st.top()==0) st.pop(); 14 i++; 15 } 16 else{ 17 while(i<size&&preorder[i]!=',') i++; 18 st.top()-=1; 19 if(st.top()==0) st.pop(); 20 st.push(2); 21 } 22 } 23 return st.empty(); 24 } 25 };
可以发现上述是通过计数栈里的槽位是否能和preorder的元素数相同,能刚好消耗完成,相当于我们可以用一个计数器,模拟槽位的消耗和增加,其余的都是一样的。
1 class Solution { 2 public: 3 bool isValidSerialization(string preorder) { 4 int size=preorder.length(); 5 int cnt=1; 6 int i=0; 7 while(i<size){ 8 if(cnt==0) return false; 9 if(preorder[i]==',') i++; 10 else if(preorder[i]=='#'){ 11 cnt--; 12 i++; 13 } 14 else{ 15 while(i<size&&preorder[i]!=',') i++; 16 cnt++; 17 } 18 } 19 return cnt==0; 20 } 21 };

浙公网安备 33010602011771号