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

题目分析:

题目意思是给定一个字符串序列,然后判断这个字符串序列是不是一个二叉树的先序序列化(先序序列化即按先序遍历二叉树,遍历的元素生成字符串序列,如果叶节点没有元素则是“#”)
我们可以从二叉树的生成考察序列化#和元素个数的关系,开头我们假设能容纳#的值为count1,count1值为1,已有元素的值为count2,count2值为0,当有一个元素生成count2++,此时生成两个叶节点,可以容纳#的位置多了两个,count1+=2.当再有一个元素生成时,能容纳#的位置少了一个,count1--,count2++,但是当元素生成后又生成两个叶节点,count1+=2,这样一来一回相当于count1++和count2++,最后无论二叉树的生成是怎样,count1始终都是count2+1,而且在考察的时候我们是按根->叶节点的顺序考察的,对应了二叉树的先序序列顺序,也就是说,字符串序列应当是先有元素再有#,而且在序列生成一个#或者元素的时候前面的#个数要小于count2+1,也即不能超出前面序列给出的能容纳的#的值。

c++代码:

class Solution {
public:
    bool isValidSerialization(string preorder) {
        istringstream in(preorder);
        vector<string> v;
        string t = "";
        while (getline(in, t, ',')) v.push_back(t);
        //因为能容纳的#个数必定是已有元素个数+1,因此不用记录,反之要记录已有的#个数
        //cnt1表示已有的#个数,cnt2表示已有的元素个数
        int cnt1 = 0, cnt2 = 0;
        for (int i = 0; i < v.size(); i++) {
            if (v[i] == ",") {
                continue;
            }
            if (v[i] == "#") {
                if (cnt1 >= cnt2 + 1) return false;
                cnt1++;
            }
            else {
                if (cnt1 >= cnt2 + 1) return false;
                cnt2++;
            }
        }
        if (cnt1 == cnt2 + 1) return true;
        return false;
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值