题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
解题思路:
1.把二叉树的根结点存入队列
2.从队首取出元素存入容器中
3.如果存在子结点,子结点插入到队尾
4.循环2,3过程直到队列为空
代码实现:
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
#include<queue>
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
/*
解题思路:
1.把二叉树的根结点存入队列
2.从队首取出元素存入容器中
3.如果存在子结点,子结点插入到队尾
4.循环2,3过程直到队列为空
*/
vector<int> result;
if(root == NULL){
return result;
}
queue<TreeNode*> q;
TreeNode* currentNode;
q.push(root);
while(!q.empty()){
currentNode = q.front();
result.push_back(currentNode->val);
q.pop();
if(currentNode->left != NULL){
q.push(currentNode->left);
}
if(currentNode->right != NULL){
q.push(currentNode->right);
}
}
return result;
}
};