LeetCode Solutions

331. Verify Preorder Serialization of a Binary Tree

Time: $O(n)$

Space: $O(n)$

			

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;
  }
};
			

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;
  }
}
			

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