依次打印二叉樹(shù)

今天做了兩題,是同一個(gè)系列,都是打印二叉樹(shù)中的值,不同之處在于一個(gè)分層一個(gè)不分層。很典型的BFS的解法。
關(guān)鍵點(diǎn)基本上是兩點(diǎn):

  1. 邊界條件的檢測(cè),即:root為空時(shí)返回空的vector;
  2. 使用隊(duì)列 queue存儲(chǔ)節(jié)點(diǎn),當(dāng)隊(duì)列為空時(shí),說(shuō)明遍歷完畢。
    (此處順便復(fù)習(xí)一下queue最基本的用法:
queue<int> q;
q.push(3);    // q = [3]
q.push(5);    // q = [3, 5]
int val = q.front();      // val = 3
q.pop();    // q = [5];

(題目為劍指offer 32 Ⅰ、Ⅱ,題目?jī)?nèi)容不再贅述,下邊直接貼代碼)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> levelOrder(TreeNode* root) {
        if (root == nullptr) {
            return {};
        }
        vector<int> temp;
        queue<TreeNode*> nodes;
        TreeNode* node;
        nodes.push(root);
        while (!nodes.empty()) {
            node = nodes.front();
            nodes.pop();
            temp.push_back(node->val);
            if (node->left) {
                nodes.push(node->left);
            }
            if (node->right) {
                nodes.push(node->right);
            }
        }
        return temp;
    }
};

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        if (root == nullptr) {
            return {{}};
        }
        vector<vector<int>> res;
        queue<TreeNode*> nodes;
        TreeNode* node;
        nodes.push(root);
        while (!nodes.empty()) {
            int size = nodes.size();
            vector<int> temp;
            // for (int i = 0; i < size; ++i) {
            while (!nodes.empty()) {
                node = nodes.front();
                temp.push_back(node->val);
                nodes.pop();
            }
            res.push_back(temp);
            temp.clear();
            if (node->left) {
                nodes.push(node->left);
            }
            if (node->right) {
                nodes.push(node->right);
            }
        }
        return res;
    }
};
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容