[LeetCode]Verify Preorder Serialization of a Binary Tree

来源:互联网 发布:软件质量保证计划事例 编辑:程序博客网 时间:2024/05/16 12:16
如果在还未完全遍历整个树的时候就已经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("#");    }}



0 0
原创粉丝点击