1. 程式人生 > >劍指Offer —— BFS 寬度優先打印

劍指Offer —— BFS 寬度優先打印

bottom color 打印 node views 描述 Coding .net nbsp

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; } };

劍指Offer —— BFS 寬度優先打印