/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
@Freeich 对的,如果不是字面量的拼接,使用的就是StringBuilder。String s = s1+s2;对应的就是StringBuilder sb = new StringBuilder(),sb.append(s1),sb.append(s2)。然后返回时调用sb.toString(),这个toString()一般来说看源码的话就是new String(),这样一来新建了一个String对象,所以占用内存
*/
using namespace std;
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string res = “”;
if(!root) return “”;
queue<TreeNode> q;
q.push(root);
TreeNode cur = new TreeNode(0);
while(!q.empty()){
int len = q.size();
while(len–){
cur = q.front();
q.pop();
if(!cur){
res.push_back(‘$’);
}else{
res.append(to_string(cur->val));
}
res.push_back(‘,’);
if(cur!=nullptr){
q.push(cur->left);
q.push(cur->right);
}
}
}
res.pop_back();
return res;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data.size()==0) return nullptr;
int len = data.size();
int i = 0;
vector<TreeNode*> vec;
while(i < len){
string str = "";
while(i < len && data[i] != ','){
str.push_back(data[i]);
i++;
}
if(str == "$"){
TreeNode *temp = nullptr;
vec.push_back(temp);
}else{
int temp = stoi(str);
TreeNode* cur = new TreeNode(temp);
vec.push_back(cur);
}
i++;
}
int j = 1;
for(int i = 0; j < vec.size(); i++){
if(vec[i] == nullptr) continue;
if(j<vec.size()) vec[i]->left = vec[j++];
if(j<vec.size()) vec[i]->right = vec[j++];
}
return vec[0];
}
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string res;
if (!root) return res;
queue<TreeNode*> que;
que.push(root);
while (!que.empty()) {
TreeNode* front = que.front();
que.pop();
if (front != nullptr) {
res += to_string(front->val) + ",";
que.push(front->left);
que.push(front->right);
}
else {
res += "null,";
}
}
return res;
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if (data.empty()) return nullptr;
vector<string> s = split(data);
queue<TreeNode*> que;
TreeNode* root = new TreeNode(stoi(s[0]));
que.push(root);
int i = 1; // 因为这里root已经被处理了,所以i从1开始
while (!que.empty()) {
TreeNode* front = que.front();
que.pop();
if (s[i] != "null") {
front->left = new TreeNode(stoi(s[i]));
que.push(front->left);
}
i++;
if (s[i] != "null") {
front->right = new TreeNode(stoi(s[i]));
que.push(front->right);
}
i++;
}
return root;
}
vector<string> split(string& s) {
// cout << s << endl;
vector<string> res;
int n = s.size();
int i = 0;
while (i < n) {
int j = i + 1;
while (j < n && s[j] != ',') j++;
res.push_back(s.substr(i, j - i));
i = j + 1;
}
return res;
}
java 有点取巧了
public class Codec {
private TreeNode root;
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
this.root =root;
return null;
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
return root;
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
//序列化成字符串,1,2,3,null,null,4,5,null...
if(root == null){
return "";
}
StringBuilder bulid = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode t = queue.poll();
if(t != null){
queue.add(t.left);
queue.add(t.right);
bulid.append(t.val + ",");
}else{
bulid.append("null,");
}
}
return bulid.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data == null || data.length() <= 0){
return null;
}
String [] s = data.split(",");
Queue<TreeNode> queue = new LinkedList<>();
TreeNode root = new TreeNode(Integer.parseInt(s[0]));
queue.add(root);
int i = 1;
while(!queue.isEmpty()){
TreeNode t = queue.poll();
//构建左节点
if(!s[i].equals("null")){
TreeNode left = new TreeNode(Integer.parseInt(s[i]));
t.left = left;
queue.add(left);
}
i++;
//构建右节点
if(!s[i].equals("null")){
TreeNode right = new TreeNode(Integer.parseInt(s[i]));
t.right = right;
queue.add(right);
}
i++;
}
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
十一
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if (root == null) return "[]";
StringBuilder res = new StringBuilder("[");
Queue<TreeNode> queue = new LinkedList<>() {{ add(root); }};
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node != null) {
res.append(node.val + ",");
queue.add(node.left);
queue.add(node.right);
} else {
res.append("null,");
}
}
res.deleteCharAt(res.length() - 1);
res.append("]");
return res.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data.equals("[]")) return null;
String[] vals = data.substring(1, data.length() - 1).split(",");
TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
Queue<TreeNode> queue = new LinkedList<>() {{ add(root); }};
int i = 1;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (!vals[i].equals("null")) {
node.left = new TreeNode(Integer.parseInt(vals[i]));
queue.add(node.left);
}
i++;
if (!vals[i].equals("null")) {
node.right = new TreeNode(Integer.parseInt(vals[i]));
queue.add(node.right);
}
i++;
}
return root;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
public class Codec {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
if(root==null){
return "";
}
StringBuilder builder = new StringBuilder();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode t = queue.poll();
if(t!=null){
queue.add(t.left);
queue.add(t.right);
builder.append(t.val+",");
}else{
builder.append(null+",");
}
}
return builder.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if(data==null||data.length()<=0){
return null;
}
String[] s = data.split(",");
Queue<TreeNode> queue = new LinkedList<>();
TreeNode root = new TreeNode(Integer.parseInt(s[0]));
queue.add(root);
int i = 1;
while(!queue.isEmpty()){
TreeNode t = queue.poll();
if(!s[i].equals("null")){
TreeNode left = new TreeNode(Integer.parseInt(s[i]));
t.left = left;
queue.add(left);
}
i++;
if(!s[i].equals("null")){
TreeNode right = new TreeNode(Integer.parseInt(s[i]));
t.right = right;
queue.add(right);
}
i++;
}
return root;
}
}
public class Codec {
int index = 0; // 全局索引
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
toStr(root,sb);
return sb.toString();
}
public void toStr(TreeNode root, StringBuilder sb) {
if(root == null) {
sb.append("#,");
return ;
}
sb.append(root.val).append(",");
toStr(root.left,sb);
toStr(root.right,sb);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
return toTree(data.split(","),index);
}
public TreeNode toTree(String[] nodes, int k) {
if(index > nodes.length || "#".equals(nodes[index])) {
return null;
}
TreeNode root = new TreeNode(Integer.parseInt(nodes[index]));
root.left = toTree(nodes, index ++);
root.right = toTree(nodes, index ++);
return root;
}
}
/** 使用前序遍历
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
// Encodes a tree to a single string.
List<String> list = new ArrayList<>();
int index = 0;
public String serialize(TreeNode root) {
String ans = "";
if (root == null)
return ans;
preOrderSer(root);
ans = list.stream().collect(Collectors.joining(","));
return ans;
}
public void preOrderSer(TreeNode node) {
list.add(String.valueOf(node.val));
if (node.left == null)
list.add("x");
else
preOrderSer(node.left);
if (node.right == null)
list.add("x");
else
preOrderSer(node.right);
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if (data.length() == 0)
return null;
String[] array = data.split(",");
return preOrderDes(array);
}
public TreeNode preOrderDes(String[] array) {
if(array[index].equals("x"))
{
return null;
}
TreeNode node = new TreeNode(Integer.valueOf(array[index]));
index++;
node.left = preOrderDes(array);
index++;
node.right = preOrderDes(array);
return node;
}
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
共以下 24 个回答
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
@Freeich 对的,如果不是字面量的拼接,使用的就是StringBuilder。String s = s1+s2;对应的就是StringBuilder sb = new StringBuilder(),sb.append(s1),sb.append(s2)。然后返回时调用sb.toString(),这个toString()一般来说看源码的话就是new String(),这样一来新建了一个String对象,所以占用内存
*/
using namespace std;
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
string res = “”;
if(!root) return “”;
queue<TreeNode> q;
q.push(root);
TreeNode cur = new TreeNode(0);
while(!q.empty()){
int len = q.size();
while(len–){
cur = q.front();
q.pop();
if(!cur){
res.push_back(‘$’);
}else{
res.append(to_string(cur->val));
}
res.push_back(‘,’);
if(cur!=nullptr){
q.push(cur->left);
q.push(cur->right);
}
}
}
res.pop_back();
return res;
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
class Codec {
public:
};
序列化:
打印null值的层序遍历
反序列化:通过队列一层一层构建二叉树
时间复杂度:O(n)
空间复杂度:O(n)
时间复杂度:O(n)
空间复杂度:O(n)
java 有点取巧了
public class Codec {
private TreeNode root;
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
this.root =root;
return null;
}
}
好意思吗哈哈哈
最后两个测试用例没有通过
字符串操作还得记一下
十一
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Codec {
}
// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
时间:O(n)
空间:O(n)
/**
* 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:
};
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
”’java
public class Codec {
}
时间复杂度O(n)
空间复杂度O(n)
”’
代码
7.18
Day11:下面是代码
我的第二道困难题目…慢慢去看题解理解8成问题不大
但自己写时还是总是各种小问题不断,即使是简单题也一样
应该还是代码敲得太少了….希望我能多敲点代码
采取先序遍历 + 递归的方式
StringBuilder 可变字符串,减少空间占用
时间复杂度:O(n)
空间复杂度:O(n)
今天刚好做到,利用前序遍历
public class Codec { queue = new LinkedList<>() {{ add(root); }};
public String serialize(TreeNode root) { //层序遍历去读,变成字符串,null也记录进去
if(root null) return “[]”;
StringBuilder res = new StringBuilder(“[“);
Queue
while(!queue.isEmpty()) {
TreeNode node = queue.poll();
if(node != null) {
res.append(node.val + “,”);
queue.add(node.left);
queue.add(node.right);
}
else res.append(“null,”);
}
res.deleteCharAt(res.length() – 1);
res.append(“]”);
return res.toString();
}
}