331. Verify Preorder Serialization of a Binary Tree
tag:1、使用stack
2、考虑特殊情况“#”, “##”,字符串还没有遍历完便已得到一颗完整的二叉树
3、还可以从n0=n2+1考虑。
方法1:
struct node
{
int lt,rt;
int v;
};
void split(string s,char c,vector<int>& vt)
{
int i;
int ans=0;
for(i=0;s[i]!='\0';i++)
{
if(s[i]==c)
{
vt.push_back(ans);
ans=0;
}
else if(s[i]=='#')
{
ans=-1;
}
else
ans=ans*10+s[i]-'0';
}
vt.push_back(ans);
}
class Solution {
public:
bool isValidSerialization(string preorder) {
vector<int> vt;
stack<node> st;
split(preorder, ',', vt);
int len=vt.size();
int i;
for(i=0;i<len;i++)
{
if(vt[i]!=-1)
{
node n;
n.lt=n.rt=0;
n.v=vt[i];
st.push(n);
}
else
{
if(st.empty())
break;
while(!st.empty())
{
node n=st.top();
if(n.lt==0)
{
n.lt=-1;
st.pop();
st.push(n);
break;
}
else
{
st.pop();
}
}
if(st.empty())
break;
}
}
if(st.empty()&&i>=len-1)
return true;
else
return false;
}
};
方法2:
http://blog.csdn.net/brucehb/article/details/50638064