Java O(logn) solution using regex, trimming leaf nodes by layer.


  • 0
    I

    Explanation: If two ## follow a number, it means it is a leaf node. I replace leaf nodes with # until the root node is null.

        public boolean isValidSerialization(String preorder) {
            String prev = "";
            String curr = preorder;
            while (!curr.equals(prev)) {
                prev = curr;
                curr = curr.replaceAll("[0-9]+,#,#", "#");
    
            }
            return curr.equals("#");
        }
    }

Log in to reply
 

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