LeetCode 103 Binary Tree Zigzag Level Order Traversal 双端队列 Deque


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

Solution

由于是 /(zigzag/) 的形式,刚开始的思路是用 /(stack/) 来维护反序,但是不太自然;不如直接用双端队列来模拟(因为两头都可以 /(pop,push/))

点击查看代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    vector<vector<int>> ans;
    deque<TreeNode*> dq;
    
    
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        if(!root) return ans;
        dq.push_back(root);
        int fg = false;
        // 1: right -> left; 
        // 0: left -> right;
        while(!dq.empty()){
            vector<int> tmp;
            int sz = dq.size();
            while(sz--){
                if(!fg){
                    // left -> right
                    auto f = dq.front(); dq.pop_front();
                    if(f->left)dq.push_back(f->left);
                    if(f->right)dq.push_back(f->right);
                    tmp.push_back(f->val);
                }
                else{
                    // right -> left
                    auto f = dq.back(); dq.pop_back();
                    if(f->right)dq.push_front(f->right);
                    if(f->left)dq.push_front(f->left);
                    tmp.push_back(f->val);
                }
                
            }
            ans.push_back(tmp);
            fg = !fg;
        }
        return ans;
    }
};

原创文章,作者:254126420,如若转载,请注明出处:https://blog.ytso.com/277469.html

(0)
上一篇 2022年7月28日
下一篇 2022年7月28日

相关推荐

发表回复

登录后才能评论