美文网首页
103. Binary Tree Zigzag Level Or

103. Binary Tree Zigzag Level Or

作者: 刘小小gogo | 来源:发表于2018-08-19 12:11 被阅读0次
image.png

解法一:使用队列,读的时候用典型的BFS即可。
但是保存答案的时候,奇数不用翻转,偶数翻转。
注意reverse的用法。void reverse()

/**
 * 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>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> result;
        if(root == NULL) return result;
        vector<int> cur;
        queue<vector<TreeNode*>> q;
        cur.push_back(root->val);
        vector<TreeNode*> vcur;
        vcur.push_back(root);
        q.push(vcur);
        int flag = 1;
        result.push_back(cur);
        while(!q.empty()){
            vector<TreeNode*> myFront = q.front();
            q.pop();
            vector<int> list;
            vector<TreeNode*> plist;
            flag *= -1;
            for(int i = 0; i < myFront.size(); i++){
                if(myFront[i]->left){
                    list.push_back(myFront[i]->left->val);
                    plist.push_back(myFront[i]->left);
                }
                if(myFront[i]->right){
                    list.push_back(myFront[i]->right->val);
                    plist.push_back(myFront[i]->right);
                }
            }
            if(flag == -1){
                reverse(list.begin(), list.end());
            }
            if(plist.size()){
                q.push(plist);
                result.push_back(list);
            }

        } 
        return result;
    }
   
};

解法二:用queue

/**
 * 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>> zigzagLevelOrder(TreeNode* root) {
        queue<TreeNode*> q;
        vector<vector<int>> result;
        if(root == NULL) return result;
        q.push(root);
        bool flag = true;
        int index;
        while(!q.empty()){
            int size = q.size();
            vector<int> list(size);
            for(int i = 0; i < size; i++){
                TreeNode* node = q.front();
                q.pop();
                index = flag ? i : size - 1 - i;
                list[index] = node->val;
                if(node->left) q.push(node->left);
                if(node->right) q.push(node->right);
            }
            flag = !flag;
            result.push_back(list);
        }
        return result;
    }
};

相关文章

网友评论

      本文标题:103. Binary Tree Zigzag Level Or

      本文链接:https://www.haomeiwen.com/subject/qkkciftx.html