题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路1:非递归,层次遍历BFS,使用一个队列,每一层使用一个数组存储数据,分行打印
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> res;
vector<int> arr;
if (pRoot == nullptr)
return res;
queue<TreeNode*> q; //使用一个队列按层遍历元素
q.push(pRoot);
while (!q.empty())
{
int size = q.size(); //记录每一层的节点总个数
arr.clear(); //遍历完一层后记得clear
for (int i = 0; i < size; i++) {
TreeNode* tmp = q.front();
arr.push_back(tmp->val);
q.pop();
if (tmp->left)
q.push(tmp->left);
if (tmp->right)
q.push(tmp->right);
}
res.push_back(arr);
}
return res;
}
};
思路2:按顺序打印多行二叉树,用两个队列交错打印
【按之字形打印,可以用两个栈实现。】
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > res;
vector<int> arr;
if (pRoot == nullptr)
return res;
queue<TreeNode*> q1;
queue<TreeNode*> q2;
q1.push(pRoot);
while (!q1.empty() || !q2.empty())
{
TreeNode* tmp = nullptr;
arr.clear();
while (!q1.empty())
{
tmp = q1.front(); //q1中为当前层所有节点
arr.push_back(tmp->val);
q1.pop();
if (tmp->left)
q2.push(tmp->left); //q2中为push进下一层的所有节点
if (tmp->right)
q2.push(tmp->right);
}
if (arr.size() != 0)
res.push_back(arr);
arr.clear();
while (!q2.empty())
{
tmp = q2.front();
arr.push_back(tmp->val);
q2.pop();
if (tmp->left)
q1.push(tmp->left);
if (tmp->right)
q1.push(tmp->right);
}
if (arr.size() != 0)
res.push_back(arr);
}
return res;
}
};
思路3:利用递归的方法进行先序遍历,传递深度。递归深入一层扩容一层数组,先序遍历又保证了同层节点按从左到右入数组
>>>描述:假如一个二叉树 [1,2,3],当进入2时会创建一个 temp,此时 depth = 2,size=2;当2遍历完后会进入3,此时3 就不用创建 temp了,因为 2,3是同一层的,并且此时 depth==size 。
class Solution {
public:
vector<vector<int>> Print(TreeNode * pRoot)
{
vector<vector<int>>result;
Print(pRoot, 1, result);
return result;
}
void Print(TreeNode * pRoot, int depth, vector<vector<int>>& data)
{
if (pRoot == nullptr)
return;
if (data.size() < depth) //这个判断是用来让最左的元素创建 temp,而同一层后边的元素共用这个 temp
{
vector<int> temp;
data.push_back(temp);
}
data[depth - 1].push_back(pRoot->val);
Print(pRoot->left, depth+1,data);
Print(pRoot->right,depth+1, data);
}
};