class Solution {
public:
vector<vector<int>> levelOrder(TreeNode * root) {
vector<vector<int>> res;
queue<TreeNode*> h;
if (root==NULL) return res;
h.push(root);
while (!h.empty())
{
vector<int> tmp;
int i = h.size();
for (int j = 0; j < i; j++)
{
tmp.push_back(h.front()->val);
if (h.front()->left != NULL) h.push(h.front()->left);
if (h.front()->right!= NULL) h.push(h.front()->right);
h.pop();
}
res.push_back(tmp);
}
return res;
}
};
7. 二叉树的序列化和反序列化
注意小细节和各种函数的用法。
class Solution {
private:
vector<string> split(string &data,string delim) {
vector<string> results;
int i=0;int j=0;
//如果不存在,返回的是string::npos
while (data.find(delim,j)!=string::npos) {
i=data.find(delim,j);
results.push_back(data.substr(j,i-j));
j=i+delim.length();
}
if (j!=data.length()) {
results.push_back(data.substr(j,data.length()-j));
}
return results;
}
public:
string serialize(TreeNode * root) {
string res="";
if (root==NULL) return res;
queue<TreeNode*> h;
h.push(root);
res=res+to_string(root->val);
h.push(root->left);
h.push(root->right);
h.pop();
while (!h.empty()) {
if (h.front()==NULL) {
res=res+",#";
h.pop();
continue;
}
else res=res+','+to_string(h.front()->val);
h.push(h.front()->left);
h.push(h.front()->right);
h.pop();
}
//把末尾多余的,#去掉
while (res[res.size()-1]==',' ||res[res.size()-1]=='#')
res.erase(res.size()-1,1);
return res;
}
TreeNode * deserialize(string &data) {
if (data=="") return NULL;
vector<string> vals=split(data,",");
queue<TreeNode*> h;
//注意atoi(string.c_str())的用法
TreeNode * head=new TreeNode(atoi(vals[0].c_str()));
h.push(head);
for (int i=1;i<vals.size();i++) {
TreeNode *tmp=h.front();
if (vals[i]=="#") tmp->left==NULL;
else {
TreeNode *left=new TreeNode(atoi(vals[i].c_str()));
tmp->left=left;
h.push(left);
}
i++;
if (i>=vals.size()) break;
if (vals[i]=="#") tmp->right==NULL;
else {
TreeNode *right=new TreeNode(atoi(vals[i].c_str()));
tmp->right=right;
h.push(right);
}
h.pop();
}
return head;
}
};
70. 二叉树的层次遍历 II
最后把遍历结果倒过来即可。
class Solution {
public:
vector<vector<int>> levelOrderBottom(TreeNode * root) {
vector<vector<int>> res;
if (root==NULL) return res;
queue<TreeNode*> h;
h.push(root);
while (!h.empty()) {
int l=h.size();
vector<int> level;
for (int i=0;i<l;i++) {
level.push_back(h.front()->val);
if (h.front()->left !=NULL) h.push(h.front()->left);
if (h.front()->right !=NULL) h.push(h.front()->right);
h.pop();
}
res.push_back(level);
}
reverse(res.begin(),res.end());
return res;
}
};
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode * root) {
vector<vector<int>> res;
if (root==NULL) return res;
queue<TreeNode*> h;
h.push(root);
bool order=true;
while (!h.empty()) {
int l=h.size();
vector<int> level;
for (int i=0;i<l;i++) {
level.push_back(h.front()->val);
if (h.front()->left !=NULL) h.push(h.front()->left);
if (h.front()->right !=NULL) h.push(h.front()->right);
h.pop();
}
if (!orde