331. Verify Preorder Serialization of a Binary Tree

网友投稿 253 2022-09-17

331. Verify Preorder Serialization of a Binary Tree

One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node’s value. If it is a null node, we record using a sentinel value such as #.

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 ‘#’ representing null pointer.

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,#,#” Return true

Example 2: “1,#” Return false

Example 3: “9,#,#,1” Return false

class Solution public boolean isValidSerialization(String preorder) { String[] strs = preorder.split(","); int degree = -1; // root has no indegree, for compensate init with -1 for (String str : strs) { degree++; // all nodes have 1 indegree (root compensated) if (degree > 0) { // total degree should never exceeds 0 return false; } if (!str.equals("#")) {// only non-leaf node has 2 outdegree degree -= 2; } } return degree == 0; }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:645. Set Mismatch
下一篇:休克文案:这 7 句年货文案,很暖!
相关文章

 发表评论

暂时没有评论,来抢沙发吧~