Leetcode

Verify Preorder Serialization of a Binary Tree

  • Time:O(n)
  • Space:O(n)

C++

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

JAVA

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

Python

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