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; }};
- Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- Verify Preorder Serialization of a Binary Tree
- 331. Verify Preorder Serialization of a Binary Tree
- leetcode 331. Verify Preorder Serialization of a Binary Tree
- [LeetCode]331. Verify Preorder Serialization of a Binary Tree
- 331. Verify Preorder Serialization of a Binary Tree
- 【LeetCode】331. Verify Preorder Serialization of a Binary Tree
- 331. Verify Preorder Serialization of a Binary Tree
- LeetCode 331. Verify Preorder Serialization of a Binary Tree
- LeetCode *** 331. Verify Preorder Serialization of a Binary Tree
- 快速排序的java实现
- WPF中应用toolkit Chart控件安装
- PHP class 实践
- quick-cocos2d使用shader上色置灰问题
- 长见识了——text-align和margin:0 auto的作用对象及它们的不同
- 331. Verify Preorder Serialization of a Binary Tree
- openwrt 添加web界面
- Java内部类详解
- 树莓派移动网络连接(配置4G网卡)
- Java 中equals 与 == 的 区别
- 【JAVA】九 TreeMap
- Java线程池newSingleThreadExecutor newFixedThreadPool newCachedThreadPool newScheduledThreadPool
- Struts1和Struts2区别
- 信用评分之四--What Is a Hard Inquiry?(Fico信用查询之“硬查询”)