剑指Offer —— BFS 宽度优先打印

https://www.nowcoder.net/practice/7fe2212963db4790b57431d9ed259701?tpId=13&tqId=11175&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。
 
/*
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> ret;
        if (root == NULL) return ret;
        
        queue<TreeNode *> qe;
        qe.push(root);
        
        while (!qe.empty()) {
            TreeNode *tmp = qe.front();
            qe.pop();
            ret.push_back(tmp->val);
            
            if (tmp->left) qe.push(tmp->left);
            if (tmp->right) qe.push(tmp->right);
            
        }
        return ret;
    }
};
原文地址:https://www.cnblogs.com/charlesblc/p/8435793.html