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
题目分析:
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; }};
- LeetCode331. 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
- Verify Preorder Serialization of a Binary Tree
- leetcode Verify Preorder Serialization of a Binary Tree
- 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
- 331. Verify Preorder Serialization of a Binary Tree
- Prime Path POJ
- web前端面试入坑(1)
- Improving Deep Neural Networks: Hyperparameter tuning, Regularization and Optimization总结
- tomcat 开启cgi配置
- 剑指offer---数组中的逆序对
- LeetCode331. Verify Preorder Serialization of a Binary Tree
- python批量预处理图片
- C/C++中怎样获取日期和时间
- 最新最全的网站内容联盟大全
- 功能:显示所有用户
- Oracle之分析函数 之 order by子句
- Performance & Profiling
- opencv(c++)文件输入和输出使用XML和YAML文件
- 设计模式_中介者模式(25)