题目描述
从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行。
样例
输入如下图所示二叉树[8, 12, 2, null, null, 6, null, 4, null, null, null]
8
/ \
12 2
/
6
/
4
输出:[[8], [12, 2], [6], [4]]
算法1
(暴力枚举) $O(n)$
两个数组存上下两层的指针,两个数组存答案
C++ 代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> printFromTopToBottom(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;
vector<TreeNode*> first, second;
first.push_back(root);
int i = 0, j = 0;
while(i < first.size()){
auto t = first[i];
++i;
if(t->left) second.push_back(t->left);
if(t->right) second.push_back(t->right);
if(i == first.size()){
vector<int> tmp;
for(int k = 0; k < first.size(); ++k){
auto node = first[k];
tmp.push_back(node->val);
}
res.push_back(tmp);
tmp = {};
i = 0;
first = second;
second = {};
}
}
return res;
}
};
算法2
(暴力枚举) $O(n)$
还是用队列,在每一层的后面加一个标记 nullptr///在root后边加个nullptr
C++ 代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> printFromTopToBottom(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;
queue<TreeNode*> q;
q.push(root);
q.push(nullptr);
while(!q.empty() && q.front()){
vector<int> tmp;
while(q.front()){
auto t = q.front();
tmp.push_back(t->val);
q.pop();
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
q.pop();
q.push(nullptr);
res.push_back(tmp);
}
return res;
}
};