timeshark的专栏

猫头鹰是我的好朋友~

331. Verify Preorder Serialization of a Binary Tree

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:
	bool isValidSerialization(string preorder) {
		string s = spilt(preorder, ',');
		while (!s.empty()){
			if (push(s) != 0)
				return false;
			s = spilt(preorder, ',');
		}
		return mystack.size()==1 && mystack.top()=='#';
	}
	
private:
	string spilt(string& preorder, char ch){
		if (preorder.empty())
			return preorder;
		string s;
		int length = preorder.size();
		int i;
		for (i = 0; i < length; i++){
			if (preorder[i] == ch){
				s = preorder.substr(0, i);
				preorder = preorder.substr(i + 1);
				break;
			}
		}
		if (i == length){
			s = preorder;
			preorder.clear();
		}
		return s;
	}
	int push(string s){
		if (s.empty())
			return 1;
		if (s.compare("#") == 0){
			if (mystack.empty()){
				mystack.push('#');
			}
			else{
				if (mystack.top() == '#'){
					mystack.pop();
					if (mystack.empty())
						return 3;
					mystack.pop();
					while (!mystack.empty() && mystack.top() == '#'){
						mystack.pop();
						if (mystack.empty())
						return 4;
						mystack.pop();
					}
					mystack.push('#');
				}
				else{
					mystack.push('#');
				}
			}
		}
		else{
			mystack.push('t');
		}
		return 0;
	}
	stack<char> mystack;
};









阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/x_shuck/article/details/51540657
文章标签: c++
个人分类: leetcode
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

331. Verify Preorder Serialization of a Binary Tree

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭