持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第20天,点击查看活动详情
class Solution {
public:
string tree2str(TreeNode* root) {
string ss;
treecopy(root,ss);
return ss;
}
void treecopy(TreeNode* root,string& str) //传引用减少构造
{
if(root == nullptr)
return ;
str+= to_string(root->val);
if(root->left || root -> right)
{
str+="(";
treecopy(root->left,str);
str+=")";
}
if(root->right)
{
str+="(";
treecopy(root->right,str);
str+=")";
}
}
};
利用的是前序遍历
题目描述:(题目链接)
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> vv;
if(root ==nullptr)
return vv;
queue<TreeNode*> q;
q.push(root);
int numsize =1;
while(!q.empty())
{
//一层一层的遍历
vector<int> v;
for(int i=0;i<numsize;i++)
{
TreeNode* cur = q.front();
q.pop();
v.push_back(cur->val);
if(cur->left)
q.push(cur->left);
if(cur->right)
q.push(cur->right);
}
vv.push_back(v);
numsize = q.size();
}
return vv;
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
vector<vector<int>> vv;
if(root ==nullptr)
return vv;
queue<TreeNode*> q;
q.push(root);
int numsize =1;
while(!q.empty())
{
TreeNode* cur = q.front(); //取出队列的头
v.push_back(cur->val);
q.pop();
numsize--;
if(cur->left)
q.push(cur->left);
if(cur->right)
q.push(cur->right);
if(numsize==0)
{
vector<int> tem =v;
v.clear();
vv.push_back(tem);
numsize = q.size();
}
}
return vv;
}
};
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode* root) {
vector<vector<int>> vv;
if(root ==nullptr)
return vv;
queue<TreeNode*> q;
q.push(root);
int numsize =1;
while(!q.empty())
{
//一层一层的遍历
vector<int> v;
for(int i=0;i<numsize;i++)
{
TreeNode* cur = q.front();
q.pop();
v.push_back(cur->val);
if(cur->left)
q.push(cur->left);
if(cur->right)
q.push(cur->right);
}
numsize =q.size();
vv.push_back(v);
}
reverse(vv.begin(),vv.end());
return vv;
}
};
reverse一下就得到了