#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
/*
问题:
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
分析:给定二叉树的前序序列化结果,判断该结果是否正确。
首先,题目要求空结点用#表示,必定是一个满二叉树(除叶节点,每个结点都有两个孩子)
而满二叉树总结点个数=2^h - 1,其中h为二叉树的高度,从1开始。
错,不一定是满二叉树。如果当前结点为空,后续两个结点都为空
前序:根左右,前序遍历的迭代算法是:使用栈,由于先要访问做孩子,那么优先压入右孩子
初始:压入根节点
1】栈不空,弹出当前结点,如果当前结点右孩子不空,压入右孩子,如果当前结点左孩子不空,压入左孩子
2】如果当前结点是叶节点,转1】
先简单化问题:
如果允许构建树,那么如何构建:
一个结点后面如果有两个#,表示该结点为叶子结点
一个结点如果不空,后面两个元素就是其左右孩子
关键:
参见解法:http://blog.csdn.net/gao1440156051/article/details/51993212
采用每次X##这种,就弹出X##,弹入一个#,如果最后只剩一个#,说明成功
主要就是根据空结点为##,然后把后续叶节点消除,使得叶节点的父节点消除,
直到最后所有结点都消除,变成一个#
输入:
9,3,4,#,#,1,#,#,2,#,6,#,#
1,#
9,#,#,1
输出:
true
false
false
*/
class Solution {
public:
bool isValidSerialization(string preorder) {
if(preorder.empty())
{
return false;
}
vector<string> strs;
int len = preorder.length();
stringstream stream(preorder);//将字符串转化为输入流
string value;
while(getline(stream , value , ','))//getline(输入流,存储的字符串,分隔符)
{
strs.push_back(value);
int size = strs.size();
while(size >= 3 && "#" == strs.at(size - 1) && "#" == strs.at(size - 2) && strs.at(size - 3) != "#")
{
strs.pop_back();
strs.pop_back();
strs.pop_back();
strs.push_back("#");
size = strs.size();
}
}
return ( 1 == strs.size() && "#" == strs.at(0) );
}
};
void process()
{
Solution solution;
const int MAXSIZE = 1024;
char str[MAXSIZE];
while(gets_s(str))
{
string preorder(str);
bool result = solution.isValidSerialization(preorder);
if(result)
{
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
}
}
int main(int argc , char* argv[])
{
process();
getchar();
return 0;
}
leecode 解题总结:331. Verify Preorder Serialization of a Binary Tree
最新推荐文章于 2024-08-26 07:28:39 发布