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;
    }
};
全部评论

相关推荐

02-28 01:18
已编辑
南昌大学 后端工程师
黑皮白袜臭脚体育生:把开源经历放个人项目上边应该更好,就像大部分人都把实习经历放个人项目上边
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务