leetcode331Verify Preorder Serialization of a Binary Tree
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
這道題目也是自己沒相處方法,去翻了别人的部落格。二叉樹的特性,就是每在一個空節點上插入1個葉節點的話,原先的空節點消失,新增2個空節點,是以二叉樹的空節點最終比所有有值的節點多1,由這點入手。統計字元串序列中空節點和有值節點的個數,在不考慮最後一個節點的情況,空節點個數和有值節點個數應該相同,并且最後一個節點一定為#。除去隻有一個節點并且該節點是#的情況,其他情況下,第一個節點必定不為#。
class Solution {
public:
bool isValidSerialization(string preorder) {
if (preorder.empty())
{
return false;
}
istringstream input(preorder);
vector<string> vs;
string temp;
int count = 0;
while (getline(input, temp, ','))
{
vs.push_back(temp);
}
for (int i = 0; i < vs.size() - 1; ++i)
{
if (vs[i] == "#")
{
if (count == 0)
{
return false;
}
else
{
--count;
}
}
else
{
count++;
}
}
if (count == 0 && vs.back() == "#")
{
return true;
}
else
{
return false;
}
}
};