二叉树被记录成文件的过程叫做二叉树的序列化。序列化的方法有很多,这里我们采用括号序列的方法将其序列化,所谓括号序列指的是对于一个节点生成一个括号,括号内是其子树的括号序列,其中左儿子(若存在)的括号在前,右儿子(若存在)的括号在后。对于给定的树,请设计高效的算法,将其序列化。
给定一个树的根节点指针root,请返回一个字符串,代表其序列化后的括号序列。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class TreeToSequence {
public:
void tostring(TreeNode* root,string &res)
{
if(root)
{
res.push_back('(');
tostring(root->left,res);
//res.push_back('(');
//res.push_back(')');
tostring(root->right,res);
res.push_back(')');
}
}
string toSequence(TreeNode* root) {
string res;
tostring(root,res);
return res;
}
};
class TreeToSequence {
public:
string getAns(TreeNode *root){
string temp;
if(!root) return temp;
string s1,s2;
if(root->left)
s1 = getAns(root->left);
if(root->right)
s2 =getAns(root->right);
temp+='(';
temp+=s1;
temp+=s2;
temp+=')';
return temp;
}
string toSequence(TreeNode* root) {
string ans;
if(!root) return ans;
ans=getAns(root);
return ans;
}
};
/*后序遍历*/
class TreeToSequence {
public:
string toSequence(TreeNode* root) {
if (!root) return "";
ostringstream s;
s << '(';
if (root->left) s << toSequence(root->left);
if (root->right) s << toSequence(root->right);
s << ')';
return s.str();
}
}; class TreeToSequence {
public:
string toSequence(TreeNode* root) {
string result;
Fun(root,result);
return result;
}
void Fun(TreeNode *root, string &result){
if(root)
{ result.push_back('('); Fun(root->left, result); Fun(root->right, result); result.push_back(')'); } }
};
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
public class TreeToSequence {
public String toSequence(TreeNode root) {
// write code here
String str="";
if(root==null){
return "";
}else{
str="(";
str+=toSequence(root.left);
str+=toSequence(root.right);
str+=")";
return str;
}
}
}
c++代码,前序遍历的思想
class TreeToSequence {
public:
string toSequence(TreeNode* root) {
// 前序遍历
if(root==nullptr) return "";
string res = '(' + forward_order(root) + ')';
return res;
}
string forward_order(TreeNode* node)
{
if(node==nullptr) return "";
string res;
//res.push_back(node->val);
if(node->left!=nullptr)
res += '(' + forward_order(node->left) + ')';
if(node->right!=nullptr)
res += '(' + forward_order(node->right) + ')';
return res;
}
}; /*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class TreeToSequence {
public:
string toSequence(TreeNode* root) {
if(!root) return "";
return "("+toSequence(root->left)+toSequence(root->right)+")";
}
}; class TreeToSequence {
public:
string core(TreeNode* cur)
{
string out="";
if(cur==nullptr)
return out;
if(cur->left)
out="("+core(cur->left)+")"+out;
if(cur->right)
out=out+"("+core(cur->right)+")";
return out;
}
string toSequence(TreeNode* root) {
return "("+core(root)+")";
}
};