题目:
One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #
.
_9_ / \ 3 2 / \ / \ 4 1 # 6 / \ / \ / \ # # # # # #
For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#"
, where #
represents a null node.
Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.
Each comma separated value in the string must be either an integer or a character '#'
representing null
pointer.
You may assume that the input format is always valid, for example it could never contain two consecutive commas such as "1,,3"
.
Example 1:
"9,3,4,#,#,1,#,#,2,#,6,#,#"
Return true
Example 2:
"1,#"
Return false
Example 3:
"9,#,#,1"
Return false
题目分析:
c++代码:
class Solution {
public:
bool isValidSerialization(string preorder) {
istringstream in(preorder);
vector<string> v;
string t = "";
while (getline(in, t, ',')) v.push_back(t);
//因为能容纳的#个数必定是已有元素个数+1,因此不用记录,反之要记录已有的#个数
//cnt1表示已有的#个数,cnt2表示已有的元素个数
int cnt1 = 0, cnt2 = 0;
for (int i = 0; i < v.size(); i++) {
if (v[i] == ",") {
continue;
}
if (v[i] == "#") {
if (cnt1 >= cnt2 + 1) return false;
cnt1++;
}
else {
if (cnt1 >= cnt2 + 1) return false;
cnt2++;
}
}
if (cnt1 == cnt2 + 1) return true;
return false;
}
};