Java Concise Solution


  • 0
    public class Solution {
        public boolean isValidSerialization(String preorder) {
            if (preorder == null || preorder.length() == 0) return false;
            String[] arr = preorder.split(",");
            if (arr[0].equals("#") && arr.length == 1) return true;
            if (arr[0].equals("#") && arr.length > 1) return false;
            int outDegree = 2;
            for (int i = 1; i < arr.length; i++) {
                if (outDegree == 0) return false; //means no more open port but still have some in the array, conflict
                outDegree--;
                if (!arr[i].equals("#")) outDegree += 2;
            }
            return outDegree == 0;
        }
    }
    

Log in to reply
 

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