331. Verify Preorder Serialization of a Binary Tree

#.

     _9_
    /   \
   3     2
  / \   / \
 4   1  #  6
/ \ / \   / \
# # # #   # #

For example, the above binary tree can be serialized to the string"9,3,4,#,#,1,#,#,2,#,6,#,#", where#represents a null node.

Given a string of comma separated values, verify whether it is a correct preorder traversal serialization of a binary tree. Find an algorithm without reconstructing the tree.

Each comma separated value in the string must be either an integer or a character'#'representingnullpointer.

You may assume that the input format is always valid, for example it could never contain two consecutive commas such as"1,,3".

Example 1:
"9,3,4,#,#,1,#,#,2,#,6,#,#"
Returntrue

Example 2:
"1,#"
Returnfalse

Example 3:
"9,#,#,1"
Returnfalse

class Solution {
    public boolean isValidSerialization(String preorder) {
        if (preorder == null || preorder.length() == 0) return true;
        int diff = 1;

        for (String str : preorder.split(",")){
            if (--diff < 0) return false;
            if (!str.equals("#")) diff += 2;
        }

        return diff == 0;
    }
}
class Solution {
    public boolean isValidSerialization(String preorder) {
        String[] strs = preorder.split(",");

        return dfs(strs, 0) == strs.length;
    }

    private int dfs(String[] strs, int index){
        if (index >= strs.length) return -1;

        if (strs[index].equals("#")) return 1;

        int leftLen = dfs(strs, index + 1);
        if (leftLen == -1) return -1;
        int rightLen = dfs(strs, index + 1 + leftLen);
        if (rightLen == -1) return -1;

        return 1 + leftLen + rightLen;
    }
}

results for ""

    No results matching ""