Java, using Queue


  • 0
    D
    public class Solution {
        public boolean isValidSerialization(String preorder) 
        {
            if (preorder == null || preorder.length() < 1) { return false; }
            // using queue
            Queue<String> que = new LinkedList<>();
            // note here is string!, it contains ","!
            String[] pre = preorder.split(",");
            
            int len = pre.length;
            // add tree root
            int i = 0;
            que.add(pre[i++]);
            
            while (!que.isEmpty())
            {
                String c = que.poll();
                if (!c.equals("#"))
                {
                    if (i + 2 <= len) { que.add(pre[i++]); que.add(pre[i++]); }
                    // not enough node, return false
                    else { return false; }
                }
            }
            // too many node
            if (i != len) { return false; }
            
            return true;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.