LeetCode331. Verify Preorder Serialization of a Binary Tree

来源:互联网 发布:安全风险评估矩阵 编辑:程序博客网 时间:2024/06/06 04:20

题目:

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;    }};


原创粉丝点击