Skip to content

331. Verify Preorder Serialization of a Binary Tree 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  bool isValidSerialization(string preorder) {
    int degree = 1;  // outDegree (children) - inDegree (parent)
    istringstream iss(preorder);

    for (string node; getline(iss, node, ',');) {
      if (--degree < 0)
        return false;
      if (node != "#")
        degree += 2;
    }

    return degree == 0;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public boolean isValidSerialization(String preorder) {
    int degree = 1; // outDegree (children) - inDegree (parent)

    for (final String node : preorder.split(",")) {
      if (--degree < 0) // one parent
        return false;
      if (!node.equals("#"))
        degree += 2; // two children
    }

    return degree == 0;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def isValidSerialization(self, preorder: str) -> bool:
    degree = 1  # outDegree (children) - inDegree (parent)

    for node in preorder.split(','):
      degree -= 1
      if degree < 0:
        return False
      if node != '#':
        degree += 2

    return degree == 0