链接:https://www.nowcoder.com/courses/1/7/5
来源:牛客网
有一棵二叉树,请设计一个算法,按照层次打印这棵二叉树。
给定二叉树的根结点root,请返回打印结果,结果按照每一层一个数组进行储存,所有数组的顺序按照层数从上往下,且每一层的数组内元素按照从左往右排列。保证结点数小于等于500。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class TreePrinter {
public:
vector<vector<int> > printTree(TreeNode* root) {
vector<vector<int>> result;
if(root==NULL)
return result;
queue<TreeNode*> q;
q.push(root);
TreeNode* last;
TreeNode* nlast;
vector<int> ivec;
last=root;
while(!q.empty())
{
TreeNode* t=q.front();
ivec.push_back(t->val);
q.pop();
if(t->left)
{
q.push(t->left);
nlast=t->left;
}
if(t->right)
{
q.push(t->right);
nlast=t->right;
}
if(t==last)
{
result.push_back(ivec);
ivec.clear();
last=nlast;
}
}
return result;
}
};```
二叉树序列化
链接:https://www.nowcoder.com/courses/1/7/6
来源:牛客网
首先我们介绍二叉树先序序列化的方式,假设序列化的结果字符串为str,初始时str等于空字符串。先序遍历二叉树,如果遇到空节点,就在str的末尾加上“#!”,“#”表示这个节点为空,节点值不存在,当然你也可以用其他的特殊字符,“!”表示一个值的结束。如果遇到不为空的节点,假设节点值为3,就在str的末尾加上“3!”。现在请你实现树的先序序列化。
给定树的根结点root,请返回二叉树序列化后的字符串。
测试样例:
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class TreeToString {
public:
void func1(TreeNode* root,string &s)
{
if(root==NULL)
{
s=s+”#!”;
return;
}
s=s+to_string(root->val)+”!”;
func1(root->left,s);
func1(root->right,s);
}
string toString(TreeNode* root) {
// write code here
string s;
func1(root,s);
return s;
}
};
“`