44. 分行从上往下打印二叉树
题目描述
从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行。
数据范围
树中节点的数量 [0,1000]。
样例
输入如下图所示二叉树[8, 12, 2, null, null, 6, null, 4, null, null, null]
8
/ \
12 2
/
6
/
4
输出:[[8], [12, 2], [6], [4]]
算法2 队列当中加标记
算法流程
用NULL标记行结束
时间复杂度
$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;
queue<TreeNode*> q;
q.push(root);
q.push(nullptr); //层结束标识符
vector<int> level;
while(q.size())
{
auto t = q.front();
q.pop();
if(!t) //遇到层结束符时一定当前层所有孩子都已被记录
{
if(level.empty()) break; //必须要这个判断,判断树是否遍历完
res.push_back(level);
level.clear();
q.push(nullptr);
continue;
}
level.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
return res;
}
};
算法1 BFS+哈希表
算法流程
整体用宽度优先层序遍历
用哈希表记录下每个节点的层数,左右孩子刚好是父节点的下一层
每次队列弹出元素时检查是否层数发生变化,变化则说明到了下一层,需要结算当前层
每一层用tmp数组记录
结算操作:
- 插入tmp数组内容
- 清空tmp数组
- 当前层编号修改
复杂度
时间复杂度 $O(n)$ – 遍历每个节点,每次循环操作$O(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;
vector<int> tmp;
if(!root) return res;
unordered_map<TreeNode*, int> nodesLevel;
int curLevel = 0;
queue<TreeNode*> q;
nodesLevel[root] = curLevel;
q.push(root);
while(q.size())
{
auto t = q.front();
q.pop();
if(nodesLevel[t] != curLevel) //结算先前层
{
res.push_back(tmp);
tmp.clear();
curLevel = nodesLevel[t];
}
tmp.push_back(t->val); //记录当前层
if(t->left)
{
nodesLevel[t->left] = curLevel + 1;
q.push(t->left);
}
if(t->right)
{
nodesLevel[t->right] = curLevel + 1;
q.push(t->right);
}
}
res.push_back(tmp); //加上最后一层
return res;
}
};