题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
解法一:
这个题和之字形打印很像,这里我们直接使用两个双端队列就好了deq_1, deq_2。
思路如下
- 根节点指针放入 que_1,根据 que_1中的元素,可以得到其对应的左右孩子,也就是下一行数据,存放入 que_2
- 仿照第一步, que_2中的元素的左右孩子,用 que_1来存放
- 交替执行第一、二步,直到两个队列都为空为止
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> vec;
if (!pRoot)
return vec;
int flag = 1;
queue<TreeNode*> q1;
queue<TreeNode*> q2;
q1.push(pRoot);
while (!q1.empty() || !q2.empty())
{
if (flag == 1)
{
flag = 0;
vector<int> v1;
filling(q1, q2, v1);
vec.push_back(v1);
}
else
{
flag = 1;
vector<int> v2;
filling(q2, q1, v2);
vec.push_back(v2);
}
}
return vec;
}
private:
void filling(queue<TreeNode*>& que_not_null, queue<TreeNode*>& que_null, vector<int> &v)
{
while (!que_not_null.empty())
{
TreeNode *t = que_not_null.front();
if (t->left)
que_null.push(t->left);
if (t->right)
que_null.push(t->right);
v.push_back(t->val);
que_not_null.pop();
}
}
};
解法二:
对解法一进行优化
层次遍历,每次遍历前记录当前队列当中的元素数量(感觉写到这,你就应该能自己写出代码了)
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> vec;
if (!pRoot)
return vec;
queue<TreeNode*> q;
q.push(pRoot);
while (!q.empty())
{
int index = 0, curr_length = q.size();
vector<int> v;
for (index; index < curr_length; index++)
{
TreeNode* t = q.front();
if (t->left)
q.push(t->left);
if (t->right)
q.push(t->right);
v.push_back(t->val);
q.pop();
}
vec.push_back(v);
}
return vec;
}
};
解法三:
来源于牛客解法
总是有大神另辟蹊径,递归(知道方法了,现在自己去写代码吧)
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
depth(pRoot, 1);
return vec;
}
private:
void depth(TreeNode* pRoot, int dep)
{
if (!pRoot)
return;
if (dep > vec.size())
vec.push_back(vector<int>());
vec[dep - 1].push_back(pRoot->val);
depth(pRoot->left, dep + 1);
depth(pRoot->right, dep + 1);
}
private:
vector<vector<int>> vec;
};
简单总结一下吧,解法一是我最原始的思路,因为刚做完之字形打印二叉树,所以直接选择了使用两个队列。后来就想着能不能用一个队列实现,发现也可以。递归是真的没想到,不过看到递归这个想法,脑袋里就知道大致应该怎么写了。