Elegant java recursive solution (11ms)

  • 0
        public boolean isValidSerialization(String preorder) {
            if (preorder == null || preorder.length()==0) return false;
            List<String> s = Arrays.asList(preorder.split("\\,"));
            Iterator<String> it = s.iterator();
            return isTree(it) && !it.hasNext();
        private boolean isTree(Iterator<String> it){
            if (!it.hasNext())return false;
            String next = it.next();
            if ("#".equals(next)) return true;
            boolean one=isTree(it);
            boolean two=isTree(it);
            return one && two;
    It can me made prettier but I think this works too :)

Log in to reply

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