题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路:用队列装结点即可,在结点出队时,取出值并将它的存在的左右子树结点加入队列。
/*
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*> q;
vector<int> v;
if (!root) return v;
q.push(root);
while (!q.empty())
{
TreeNode* t = q.front();
v.push_back(t->val);
q.pop();
if (t->left)
q.push(t->left);
if (t->right)
q.push(t->right);
}
return v;
}
};