C++广度优先遍历
从上往下打印二叉树
http://www.nowcoder.com/questionTerminal/7fe2212963db4790b57431d9ed259701
C++广度优先遍历
使用队列进行记录,每次先左后右就能实现广度优先遍历。
代码如下
class Solution { public: vector<int> PrintFromTopToBottom(TreeNode* root) { vector <int> res; queue<TreeNode*> que; if(root!=NULL) { que.push(root); res.push_back(root->val); } while(!que.empty()){ TreeNode* tmp; tmp=que.front(); if(tmp->left!=NULL){ que.push(tmp->left); res.push_back(tmp->left->val); } if(tmp->right!=NULL){ que.push(tmp->right); res.push_back(tmp->right->val); } que.pop(); } return res; } };