본문 바로가기
알고리즘 문제풀이/leetcode

[leetcode 103] Binary Tree Zigzag Level Order Traversal

by m2162003 2020. 12. 3.

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,null,null,15,7],

 

 

 

 

 

return its zigzag level order traversal as:

 

 

 

 

 

 

문제 풀이:

기존 level 순회에서 레벨에 따라 reverse가 추가된다.

/**
 * 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 {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> result;
        vector<int> tmp;
        
        if(root == nullptr){
            return result;
        }
        queue<TreeNode*> q;
        q.push(root);
        
        
        int level = -1;
        while(!q.empty()){
            level++;
            int len = q.size();
            
            for(int i=0; i<len; i++){
                
                TreeNode* fr = q.front();
                tmp.push_back(fr->val);
                q.pop();


                if(fr -> left){
                    q.push(fr -> left);
                }

                if(fr->right){
                    q.push(fr -> right);
                }             
                    
            }
            
            if(level % 2 == 1){
                reverse(tmp.begin(), tmp.end());
            }
            result.push_back(tmp);
            tmp.clear();
        }
        return result;
    }
};

댓글