题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
解答
/*
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(NULL == root)
return result;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
TreeNode* temp=q.front();
result.push_back(temp->val);
if(temp->left)
{
q.push(temp->left);
}
if(temp->right)
{
q.push(temp->right);
}
q.pop();
}
return result;
}
};