关闭

331. Verify Preorder Serialization of a Binary Tree

标签: c++
72人阅读 评论(0) 收藏 举报
分类:

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;
};









0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:34659次
    • 积分:2602
    • 等级:
    • 排名:第13992名
    • 原创:241篇
    • 转载:4篇
    • 译文:0篇
    • 评论:0条