前序遍历结果判断二叉树是否完整的非二叉树方法
题目:
题目分析:
首先,前序遍历的特点是,(以题目示例为例)假设我们从根节点9出发,前序遍历的第一个节点是3,这时候,所有的操作都是基于3来执行的,除非3被更深的节点(4或1)覆盖(就如同3覆盖根节点9一般)或者3前序遍历结束,回到了根节点9.
这么一分析,这似乎就是栈结构嘛!
假设我们将每个节点都设置一个计数器,遇到一个非‘#’节点就将其压入栈,如果每遇到一个他的子节点,就加一,如果已经为2就将节点弹出栈(说明这个节点下面的都已经被遍历过了),如果遇到"#",只加一,不压栈。
代码:
class Solution {
public:
// Trees always have two branches, or null; And branches also have two branches, or null.
// So we create a struct that has to count whether current branches have had two branches or null
struct node{
int count;
//char myChar;
node(){
count = 0;
}
};
bool isValidSerialization(string preorder) {
stack<node> tree;
int length = preorder.length();
int index = 0;
bool hasStart = false;
if(length == 0) return false;
if(length == 1 && preorder[0] == '#') return true;
while(index < length){
// when we meet ',', ignore it
if(preorder[index] == ',')index++;
// when we first time to use stack, init it
if(!hasStart && preorder[index] != '#'){
tree.push(node());
index ++;
hasStart = true;
}else {
// if stack is empty, break
if (tree.empty())break;
// if node need to be popped
if (tree.top().count == 2) {
tree.pop();
} else {
// if we meet '#', count times without pushing it
if (preorder[index] == '#') {
tree.top().count++;
index++;
} else {
while(preorder[index] <= '9' && preorder[index] >= '0')index++;
tree.top().count++;
tree.push(node());
index++;
}
}
}
}
// popping all the node that it's count is 2
while(!tree.empty() && tree.top().count == 2) tree.pop();
// incomplete -> false
if(index < length ) return false;
else if(!tree.empty()) return false;
// complete -> true
else return true;
}
};