题目:
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,,3"这种分隔有多个逗号的情况。
题解:
考虑用堆栈来做,这个方法简单的说就是不断的砍掉叶子节点。最后看看能不能全部砍掉。
已例子一为例:”9,3,4,#,#,1,#,#,2,#,6,#,#” 遇到x # #的时候,就把它变为 #
我模拟一遍过程:
- 9,3,4,#,# => 9,3,# 继续读
- 9,3,#,1,#,# => 9,3,#,# => 9,# 继续读
- 9,#2,#,6,#,# => 9,#,2,#,# => 9,#,# => #
public boolean isValidSerialization(String preorder)
{
Stack<String> stack = new Stack<String>();
String[] num = preorder.split(",");
for(int i = 0; i < num.length; i++)
{
stack.push(num[i]);
while(stack.size() >= 3)
{
//这里必须要使用equals,如果用==就会报错
if(stack.get(stack.size() - 1).equals("#") && stack.get(stack.size() - 2).equals("#") && !stack.get(stack.size() - 3).equals("#"))
{
stack.pop();
stack.pop();
stack.pop();
stack.push("#");
}
else
break;
}
}
//注意一种特殊的情况,如果是只有一个"#",那么返回的是true,而不是false。
return stack.size() == 1 && stack.peek().equals("#");
}
此外,还需要注意一种特殊情况,也就是只有一个"#"的情况,此表示没有节点,那么返回的是true,而不是false.