序列化二叉树的一种方法是使用前序遍历。当我们遇到一个非空节点时,我们可以记录下这个节点的值。如果它是一个空节点,我们可以使用一个标记值记录,例如 #。
_9_
/ \
3 2
/ \ / \
4 1 # 6
/ \ / \ / \
# # # # # #
例如,上面的二叉树可以被序列化为字符串 "9,3,4,#,#,1,#,#,2,#,6,#,#",其中 # 代表一个空节点。
给定一串以逗号分隔的序列,验证它是否是正确的二叉树的前序序列化。编写一个在不重构树的条件下的可行算法。
每个以逗号分隔的字符或为一个整数或为一个表示 null 指针的 '#' 。
你可以认为输入格式总是有效的,例如它永远不会包含两个连续的逗号,比如 "1,,3" 。
示例 1:
输入: "9,3,4,#,#,1,#,#,2,#,6,#,#"
输出: true
示例 2:
输入: "1,#"
输出: false
示例 3:
输入: "9,#,#,1"
输出: false
要点:
(1)入度和出度必须相等。
(2)未计算到子节点,出队一定比入队大
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
/* 入度必须和出度相等,二叉树 */
bool isValidSerialization(string preorder) {
vector<char> cArr;
/* 算进根节点,入度为1,出度为2:这里设出度为减法,入度为加法 */
int dOut = -1;
for (int i = 0; i < preorder.length(); i++) {
if (preorder[i + 1] == ',') {
/* 子节点一定为'#'(空),未计算到子节点,dOut一定为负数 */
if (dOut >= 0) {
return false;
}
if (preorder[i] == '#') {
dOut += 1;
}
else {
dOut += -1;
}
}
}
if (preorder[preorder.length() - 1] == '#') {
dOut += 1;
}
else {
dOut += -1;
}
return (dOut == 0);
}
};
int main() {
string str = "9,#,92,#,#";
Solution* ps = new Solution();
cout << ps->isValidSerialization(str) << endl;
return 0;
}