LeetCode.331 Verify Preorder Serialization of a Binary Tree
来源:互联网 发布:java手机游戏安卓版 编辑:程序博客网 时间:2024/06/06 03:52
题目:
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
class Solution { public boolean isValidSerialization(String preorder) { //给定二叉树前序的字符串,判断其是否满足二叉树条件序列化条件。当节点为空时,用#替代 //思路:由于给定的序列串是满足前序条件的,根据二叉树的节点的性质。每当添加一个节点入度+1.当节点不为叶子节点,出度-2 //当出度和入度相等,说明是满足情况的序列串 String [] strs=preorder.split(","); //初始化根节点,入度为-1 int degree=-1; for(int i=0;i<strs.length;i++){ //入度+1 degree++; if(degree>0) return false; //若不是叶子节点,则出度-2 if(!strs[i].equals("#")) degree-=2; } return degree==0; }}
- [leetcode-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
- leetcode Verify Preorder Serialization of a Binary Tree
- Leetcode: Verify Preorder Serialization of a Binary Tree
- LeetCode 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
- [leetcode] Verify Preorder Serialization of a Binary Tree
- [Leetcode]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
- LeetCode Verify Preorder Serialization of a Binary Tree
- LeetCode *** 331. Verify Preorder Serialization of a Binary Tree
- [LeetCode]Verify Preorder Serialization of a Binary Tree
- LeetCode 331. Verify Preorder Serialization of a Binary Tree
- leetcode verify Preorder Serialization of a Binary Tree
- 【Leetcode】Verify Preorder Serialization of a Binary Tree
- 16-EMM Procedure 6. Handover without TAU
- Linux Oracle服务启动&停止脚本与开机自启动
- Tensorflow实战学习(二十五)【自编码器】
- Linux命令(26)——rename命令
- 17-EMM Procedure 6. Handover without TAU
- LeetCode.331 Verify Preorder Serialization of a Binary Tree
- 别再加端到端集成测试了,快换契约测试吧
- Java程序性能相关
- Html之opener对象解决父子tab页信息交换-yellowcong
- Map分支-HashMap
- 18-EMM Procedure 6. Handover without TAU
- 理解Android中的MVP架构
- HashSet
- java(33):Hibernate框架(1):基础