题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root)
{
vector<int> result;
if (root == NULL) {
return result;
}
queue<TreeNode *> Q;
Q.push(root);
while (!Q.empty()) {
int size = Q.size();
//vector<int> level;
for (int i = 0; i < size; i++) {
TreeNode *head = Q.front(); Q.pop();
//level.push_back(head->val);
result.push_back(head->val);
if (head->left != NULL) {
Q.push(head->left);
}
if (head->right != NULL) {
Q.push(head->right);
}
}
//result.push_back(level);
}
return result;
}
};