Techinpad: [LeetCode] Serialize and Deserialize Binary Tree
Question can be found /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) { if(root == NULL) return ""; vector
v; queue q; q.push(root); while(!q.empty()){ TreeNode *t = q.front(); q.pop(); if(t == NULL) { v.push_back("null"); continue; } v.push_back(to_string(t->val)); q.push(t->left); q.push(t->right); } int l = v.size() - 1; while(v[l] == "null") l--; string res = v[0]; for(int i=1;i<=l;i++){ res += "," + v[i]; } return res; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { if(0 == data.length()) return NULL; vector v; int start = 0; for(int i=1;iRead full article from Techinpad: [LeetCode] Serialize and Deserialize Binary Tree
No comments:
Post a Comment