您的位置:首页 > 其它

[LeetCode]Verify Preorder Serialization of a Binary Tree

2016-04-17 14:20 609 查看
如果在还未完全遍历整个树的时候就已经nonleaves + 1 == leaves,然而剩余未遍历的部分仍然是由若干个full tree组成的,这样整个树就不能满足nonleaves + 1 == leaves的条件。public class Solution {
public boolean isValidSerialization(String preorder) {
if(preorder == null || preorder.length() == 0) return false;
String[] cache = preorder.split(",");
int leaves = 0, nonleaves = 0, i = 0;
for (i = 0; i < cache.length && nonleaves + 1 != leaves; i++) {
if(cache[i].equals("#")) leaves++;
else nonleaves++;
}
// The given tree is a full tree, if and only if nonleaves + 1 == leaves && i == cache.length.
// Because preorder count root node first.
return nonleaves + 1 == leaves && i == cache.length;
}
}


如果在还未完全遍历整个树的时候就已经nonleaves + 1 == leaves,然而剩余未遍历的部分仍然是由若干个full tree组成的,这样整个树就不能满足nonleaves + 1 == leaves的条件。

https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/

判断一个序列是不是二叉树的前序遍历,不能重构树

解法二:

每遇到两个null就把这两个与前一个非null结合,变为null压回栈中

public class Solution {
public boolean isValidSerialization(String preorder) {
Stack<String> stack = new Stack();
String[] arr = preorder.split(",");
stack.push(arr[0]);
for (int i = 1; i < arr.length; i++) {
if (arr[i].equals("#")) {
while (stack.size() >= 2 && stack.peek().equals("#")) {
String s1 = stack.pop();
String s2 = stack.pop();
if (!(s1.equals("#") && !s2.equals("#"))) {
return false;
}
}
}
stack.push(arr[i]);
}
return stack.size() == 1 && stack.peek().equals("#");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: