Sword Finger Offer 37. Serialized Binary Tree

Title link: leetcode .

The test of this question is whether serialization and deserialization are reversible , so the form of the serialization list is not limited, as long as the two functions can be reversed each other.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 
/*
深度优先和广度优先都可以,试试广度吧,刚好可以层次遍历 

执行用时:36 ms, 在所有 C++ 提交中击败了99.03%的用户
内存消耗:28.3 MB, 在所有 C++ 提交中击败了96.07%的用户
*/
class Codec {
    
    
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
    
    
        if(root == nullptr)
			return "";
		queue<TreeNode*> Q;
		Q.push(root);
		string ans = "";
		while(!Q.empty())
		{
    
    
			TreeNode* node = Q.front();
			Q.pop();
			if(node == nullptr)
				ans += "null,";
			else
			{
    
    
				ans += to_string(node -> val);
				ans += ",";
				Q.push(node -> left);
				Q.push(node -> right);
			}
		}
		return ans; 
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
    
    
        if(data.empty())
        	return NULL;
        int N = data.size();
        int start = 0, end = 0;
        string tmp = select_num(data, start, end);
        TreeNode* root = new TreeNode(stoi(tmp));
        queue<TreeNode*> Q;
        Q.push(root);
		while(start < N)
		{
    
    
			TreeNode* node = Q.front();
			Q.pop();
			tmp = select_num(data, start, end);
        	if(tmp != "null")
        	{
    
    
        		node -> left = new TreeNode(stoi(tmp));
        		Q.push(node -> left);
        	}
        	tmp = select_num(data, start, end);
        	if(tmp != "null")
        	{
    
    
        		node -> right = new TreeNode(stoi(tmp));
        		Q.push(node -> right);
        	}
		}
		return root;
    }
    
    string select_num(const string& data, int& start, int& end)
    {
    
    
    	while(data[end] != ',')
        	end++;
        string tmp = data.substr(start, end - start);
        start = ++end;
        return tmp;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

string substr (size_t pos = 0, size_t len = npos) const;
The substring is stringa part of the object, starting at the character position posand spanning lencharacters (or until the end of the string, whichever comes first).

std::string str="We think in generalities, but we live in details.";

std::string str2 = str.substr (3,5);     // "think"

Guess you like

Origin blog.csdn.net/pppppppyl/article/details/113947645