题目描述
从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行。
数据范围
树中节点的数量 [0,1000]
。
样例
输入如下图所示二叉树[8, 12, 2, null, null, 6, null, 4, null, null, null]
8
/ \
12 2
/
6
/
4
输出:[[8], [12, 2], [6], [4]]
分行从上往下打印二叉树
/**
* 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);
while(q.size()){
int len=q.size();
vector<int>row;
while(len--){
auto t=q.front();
q.pop();
row.push_back(t->val);
if(t->left)q.push(t->left);
if(t->right)q.push(t->right);
}
res.push_back(row);
}
return res;
}
};
二叉树宽度
/**
* 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:
int maxsize;
int treeWidth(TreeNode* root) {
if(!root) return 0;
queue<TreeNode*> q;
q.push(root);
while(q.size())
{
int len=q.size();
if(len>maxsize) maxsize=len;
while(len--)
{
auto t=q.front();
q.pop();
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
}
return maxsize;
}
};