其他分享
首页 > 其他分享> > LeetCode 103 Binary Tree Zigzag Level Order Traversal 双端队列 Deque

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;
    }
};

标签:Binary,right,TreeNode,Level,双端,back,push,left,dq
来源: https://www.cnblogs.com/xinyu04/p/16527153.html