LeetCode刷题(C++)——Verify Preorder Serialization of a Binary Tree(Medium)

旧城等待, 2022-06-15 01:29 281阅读 0赞

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 #.

  1. _9_
  2. / \
  3. 3 2
  4. / \ / \
  5. 4 1 # 6
  6. / \ / \ / \
  7. # # # # # #

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

``

  1. class Solution {
  2. public:
  3. bool isValidSerialization(string preorder) {
  4. int position = 1;
  5. for(int i=0; i<preorder.size(); ++i){
  6. if(preorder[i]== ','){
  7. preorder[i] = ' ';
  8. }
  9. }
  10. istringstream out(preorder);
  11. string str;
  12. while(out>>str){
  13. if(--position < 0){
  14. return false;
  15. }
  16. if(str != "#"){
  17. position += 2;
  18. }
  19. }
  20. return position == 0;
  21. }
  22. };

发表评论

表情:
评论列表 (有 0 条评论,281人围观)

还没有评论,来说两句吧...

相关阅读