面试常考题,中序遍历用BFS。
/**
* 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;
queue<TreeNode*> q;
q.push(root);
while (q.size())
{
int size = q.size();
vector<int> level;
while (size -- ) //遍历该层的所有节点
{
TreeNode* t = q.front();
q.pop();
if (!t) continue; //跳过空节点
level.push_back(t->val); //push本层节点的值到数组
q.push(t->left); //储存下一层节点到队列
q.push(t->right);
}
if (level.size())
res.push_back(level); //push入该层的所有节点
}
return res;
}
};