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