Question:
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”
Solution
public class Solution {
public boolean isValidSerialization(String preorder) {
if (preorder == null || preorder.length() == 0) {
return false;
}
String[] str = preorder.split(",");
Stack<String> stack = new Stack<>();
for (int i = 0; i < str.length; i++) {
String cur = str[i];
while (cur.equals("#") && !stack.isEmpty() && stack.peek().equals(cur)) {
stack.pop();
if (stack.isEmpty()) {
return false;
}
stack.pop();
}
}
return (stack.size() == 1 && stack.peek().equals("#");
}
}
Note:
用一个#来替换一个数字+两个#, 最后stack里应该只剩下一个#