题解 | #从上往下打印二叉树#
从上往下打印二叉树
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) { // 广度优先算法,使用队列 std::vector<int> res; std::deque<TreeNode*> q; q.push_back(root); while(!q.empty()){ auto ele = q.front(); q.pop_front(); if(ele==nullptr){ continue; } res.push_back(ele->val); q.push_back(ele->left); q.push_back(ele->right); } return res; } };