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 #
.
|
|
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"
思路
如果我们利用栈的方法来解决,我们可以从左到右对字符串进行扫描。如果我们看到一个数字,将其入栈;如果看到#号,检查栈顶是否也为#号,如果是,一直做pop操作直到栈顶不是#号,如果不是,则将#号入栈。扫描完后检查栈的大小为1且栈顶为#即可。
我们还可以用图的出度入度来解决。
|
|
参考资料:https://discuss.leetcode.com/topic/35977/simple-python-solution-using-stack-with-explanation