[LeetCode]Binary Tree Zigzag Level Order Traversal,leetcodezigzag

來源:互聯網
上載者:User

[LeetCode]Binary Tree Zigzag Level Order Traversal,leetcodezigzag
【題目】

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3   / \  9  20    /  \   15   7

return its zigzag level order traversal as:

[  [3],  [20,9],  [15,7]]

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


【代碼一】

/**********************************   日期:2014-12-09*   作者:SJF0115*   題號: Binary Tree Zigzag Level Order Traversal*   來源:https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/*   結果:AC*   來源:LeetCode*   總結:**********************************/#include <iostream>#include <malloc.h>#include <stack>#include <vector>#include <queue>using namespace std;struct TreeNode {    int val;    TreeNode *left;    TreeNode *right;    TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution {public:    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {        vector<int> level;        vector<vector<int> > levels;        if(root == NULL){            return levels;        }        queue<TreeNode*> curq,nextq;        stack<TreeNode*> curs,nexts;        // 第index層        int index = 1;        //入隊列        curq.push(root);        // 層次遍曆        while(!curq.empty() || !curs.empty()){            //當前層遍曆            while(!curq.empty() || !curs.empty()){                TreeNode *p,*q;                // 第奇數層用佇列儲存體                if(index & 1){                    p = curq.front();                    curq.pop();                    // 第偶數層用棧儲存下一層節點                    //左子樹                    if(p->left){                        nexts.push(p->left);                        // 用於從左至右遍曆節點                        nextq.push(p->left);                    }                    //右子樹                    if(p->right){                        nexts.push(p->right);                        //用於從左至右遍曆                        nextq.push(p->right);                    }                }                // 第偶數層用棧儲存                else{                    p = curs.top();                    curs.pop();                    // 儲存節點時都是從左至右遍曆                    q = curq.front();                    curq.pop();                    // 第奇數層用佇列儲存體下一層節點                    //左子樹                    if(q->left){                        nextq.push(q->left);                    }                    //右子樹                    if(q->right){                        nextq.push(q->right);                    }                }                level.push_back(p->val);            }            index++;            levels.push_back(level);            level.clear();            swap(nextq,curq);            swap(nexts,curs);        }//while        return levels;    }};//按先序序列建立二叉樹int CreateBTree(TreeNode* &T){    char data;    //按先序次序輸入二叉樹中結點的值(一個字元),‘#’表示空樹    cin>>data;    if(data == '#'){        T = NULL;    }    else{        T = (TreeNode*)malloc(sizeof(TreeNode));        //產生根結點        T->val = data-'0';        //構造左子樹        CreateBTree(T->left);        //構造右子樹        CreateBTree(T->right);    }    return 0;}int main() {    Solution solution;    TreeNode* root(0);    CreateBTree(root);    vector<vector<int> > vecs = solution.zigzagLevelOrder(root);    for(int i = 0;i < vecs.size();i++){        for(int j = 0;j < vecs[i].size();j++){            cout<<vecs[i][j];        }        cout<<endl;    }}


【代碼二】

//廣度優先遍曆,用一個 bool 記錄是從左至右還是從右至左,每一層結束就翻轉一下。// 迭代版,時間複雜度 O(n),空間複雜度 O(n)class Solution {public:    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {        vector<int> level;        vector<vector<int> > levels;        if(root == NULL){            return levels;        }        queue<TreeNode*> queue;        // 從左至右        bool isLR = true;        //入隊列        queue.push(root);        // 層次分割標誌        queue.push(NULL);        // 層次遍曆        while(!queue.empty()){            TreeNode* p = queue.front();            queue.pop();            // 訪問當前層            if(p){                level.push_back(p->val);                // 左子節點                if(p->left){                    queue.push(p->left);                }                // 右子節點                if(p->right){                    queue.push(p->right);                }            }            // 當前層訪問完畢            else{                // 從左至右                if(isLR){                    levels.push_back(level);                }                else{                    // 反轉                    reverse(level.begin(), level.end());                    levels.push_back(level);                }                level.clear();                isLR = !isLR;                // 判斷是當前層訪問完畢還是全部訪問完畢                if(queue.size() > 0){                    queue.push(NULL);                }            }        }//while        return levels;    }};





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.