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