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 #
.
_9_ / 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:
Input:"9,3,4,#,#,1,#,#,2,#,6,#,#"
Output:true
Example 2:
Input:"1,#"
Output:false
Example 3:
Input:"9,#,#,1"
Output:false
验证二叉树的前序序列化。
序列化二叉树的一种方法是使用前序遍历。当我们遇到一个非空节点时,我们可以记录下这个节点的值。如果它是一个空节点,我们可以使用一个标记值记录,例如 #。
给定一串以逗号分隔的序列,验证它是否是正确的二叉树的前序序列化。编写一个在不重构树的条件下的可行算法。
每个以逗号分隔的字符或为一个整数或为一个表示 null 指针的 '#' 。
你可以认为输入格式总是有效的,例如它永远不会包含两个连续的逗号,比如 "1,,3" 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/verify-preorder-serialization-of-a-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我这里给一个评论区的高票答案。我们定义一个变量diff,并且把它初始化为1,代表期待的节点个数。开始遍历input,每次一开始先 diff - 1,说明已经遇到一个期待的节点了,如果此时 diff < 0 则返回false。对于一般的case而言,如果当前不是一个空节点(#),那么我们对diff += 2,意思是我期待当前这个非空节点下面还有两个节点。这样哪怕当我接下来遇到的真的是两个#的话,diff也不至于小于0。
时间O(n)
空间O(1)
Java实现
1 class Solution { 2 public boolean isValidSerialization(String preorder) { 3 String[] nodes = preorder.split(","); 4 int diff = 1; 5 for (String node : nodes) { 6 if (--diff < 0) { 7 return false; 8 } 9 if (!node.equals("#")) { 10 diff += 2; 11 } 12 } 13 return diff == 0; 14 } 15 }