题目描述
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
解答:
public static boolean isValidSerialization(String preorder) {
List<String> stack = new ArrayList<String>();
String[] arr = preorder.split(",");
for (int i = 0; i < arr.length; i++) {
stack.add(arr[i]);
while (stack.size() >= 3 && stack.get(stack.size() - 1).equals("#")
&& stack.get(stack.size() - 2).equals("#")
&& !stack.get(stack.size() - 3).equals("#")) {
stack.remove(stack.size() - 1);
stack.remove(stack.size() - 1);
stack.remove(stack.size() - 1);
stack.add("#");
}
}
if (stack.size() == 1 && stack.get(0).equals("#")) return true;
else return false;
}解法二: public static boolean isValidSerialization(String preorder) {
String[] nodes = preorder.split(",");
int diff = 1;
for (String node : nodes) {
// 入度减一
if (--diff < 0) return false;
// 出度加二
if (!node.equals("#")) diff += 2;
}
return diff == 0;
}refer:

本文介绍两种算法来验证一个字符串是否为正确的二叉树先序遍历序列化形式,无需重建树。一种使用栈结构删除叶子节点,另一种通过计算节点出入度差值判断。
563

被折叠的 条评论
为什么被折叠?



