题解 | #从上往下打印二叉树#(层次遍历)
从上往下打印二叉树
http://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701
思路
典型的层次遍历,套模板即可。
代码实现
/*
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>ans;
queue<TreeNode*>q;
if(root==nullptr) return ans;
q.push(root);
while(!q.empty())
{
TreeNode *node = q.front();
q.pop();
ans.push_back(node->val);
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
return ans;
}
};