首页 > 代码库 > LeetCode OJ 331. Verify Preorder Serialization of a Binary Tree
LeetCode OJ 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 #
.
_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:"9,3,4,#,#,1,#,#,2,#,6,#,#"
Return true
Example 2:"1,#"
Return false
Example 3:"9,#,#,1"
Return false
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
解答
这题好坑啊,逗号也要读取。用到的方法是如果是先序遍历的结果的话遍历结束后的数组NULL节点数一定比非空节点恰好多1。而这里要注意的是非空节点的键值可能在字符串数组中是多位数,并且如果字符串最后以数结尾的话,要注意此时是没有逗号的,所以不能简单的以判断逗号作为一个多位数结束的标志。
bool isValidSerialization(char* preorder) { int num = 0, ch = 0, i, j; for(i = 0; preorder[i] != 0; i = i + 2){ if(‘#‘ != preorder[i]){ num++; for(j = i; preorder[j] != ‘,‘&&preorder[j] != 0; j++); if(preorder[j] == 0) break; i = j - 1; } else{ ch++; } if(num + 1 == ch){ break; } } if(preorder[i + 1] == 0&&num + 1 == ch){ return true; } else{ return false; } }
LeetCode OJ 331. Verify Preorder Serialization of a Binary Tree