【劍指 offer】之字形打印二叉樹(shù)

1、題目描述

請(qǐng)實(shí)現(xiàn)一個(gè)函數(shù)按照之字形順序從上向下打印二叉樹(shù)。

即第一行按照從左到右的順序打印,第二層按照從右到左的順序打印,第三行再按照從左到右的順序打印,其他行以此類(lèi)推。

樣例

輸入如下圖所示二叉樹(shù)[8, 12, 2, null, null, 6, 4, null, null, null, null]
??8
? / ?\
12 2
??? / ?\
? 6 ? 4
輸出:[[8], [2, 12], [6, 4]]

2、問(wèn)題描述:

  • 之字形打印二叉樹(shù)。

3、問(wèn)題關(guān)鍵:

  • 層次打印,再加一個(gè)標(biāo)記,每次,反轉(zhuǎn)一下就可以了。

4、C++代碼:

/**
 * 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>> printFromTopToBottom(TreeNode* root) {
        vector<vector<int>> res;
        if (!root) return res;
        queue<TreeNode*> q;
        q.push(root);
        q.push(nullptr);
        bool flag = true;//為true,正向打印,false反向打印。
        vector<int> level;//保存每層遍歷的結(jié)果。
        while(q.size()) {
            auto t = q.front();
            q.pop();
            if (t) {//如果當(dāng)前層結(jié)束標(biāo)記就加入level中。
                level.push_back(t->val);
                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);
            }
            else {//如果當(dāng)前層遍歷完了,那么就將結(jié)果加入res中。
                if (level.empty()) break;//說(shuō)明把所有層都遍歷完了。
                if (flag) {//正向打印。
                    res.push_back(level);
                    flag = false;
                }
                else {
                    res.push_back(vector<int>(level.rbegin(), level.rend()));
                    flag = true;
                }
                level.clear();
                q.push(nullptr);//為下一層的最后加入標(biāo)記。
            }
        }
        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ù)。

相關(guān)閱讀更多精彩內(nèi)容

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