Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/a24a6f88b7d66721695032ac9cb8373a to your computer and use it in GitHub Desktop.
Save jianminchen/a24a6f88b7d66721695032ac9cb8373a to your computer and use it in GitHub Desktop.
Leetcode 331 - verify Preorder Serialization of a binary tree
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Leetcode331_VerifyPreorder
{
class Program
{
/*
* Leetcode 331:
* leetcode Verify Preorder Serialization of a Binary Tree
*
* In a binary tree, if we consider null as leaves, then
all non-null node provides 2 outdegree and 1 indegree (2 children and 1 parent), except root
all null node provides 0 outdegree and 1 indegree (0 child and 1 parent).
Suppose we try to build this tree. During building, we record the difference between
out degree and in degree diff = outdegree - indegree. When the next node comes, we then
decrease diff by 1, because the node provides an in degree. If the node is not null, we
increase diff by2, because it provides two out degrees. If a serialization is correct,
diff should never be negative and diff will be zero when finished.
from :https://leetcode.com/discuss/83824/7-lines-easy-java-solution
*/
static void Main(string[] args)
{
}
public static bool isValidSerialization(String preorder) {
String[] nodes = preorder.Split(',');
int outDegree = 1; // indegree
foreach (String node in nodes) {
outDegree--;
if (outDegree < 0) return false;
if (!(node.CompareTo("#") == 0))
{
outDegree += 2;
}
}
return outDegree == 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment