331. Verify Preorder Serialization of a Binary Tree

来源:互联网 发布:淘宝退货地址哪里修改 编辑:程序博客网 时间:2024/06/05 10:18

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

分析:

参考别人写的注释,提到了一个新的概念diff=出度-入度.其中内部节点的出度为2,入度为1,叶节点的出度为0,入度为1.

对于一个正确的节点系列,有diff在添加节点过程中不会小于0,且添加完后diff==0.

所以可以依据上面的概念写代码,在每添加一个节点时,都将diff减去一,若是内部节点,则在加2.

代码如下:

class Solution {public:    bool isValidSerialization(string s) {       int diff=1;       if(s.size()==0) return false;        for(int i=0;i<s.size();)        {            string temp="";            while(s[i]!=','&&i<s.size())            temp+=s[i++];            i++;            if(--diff<0) return false;            if(temp!="#") diff+=2;        }        cout<<diff;        return diff==0;    }};





0 0
原创粉丝点击