짱아의 개발 기록장

LeetCode : 103. Binary Tree Zigzag Level Order Traversal 본문

Algorithm/LeetCode

LeetCode : 103. Binary Tree Zigzag Level Order Traversal

jungahshin 2021. 1. 2. 12:07
반응형

마찬가지로, 트리를 기반으로 한 BFS문제이다.

 

[메인 로직]

queue를 pair형태로 다음과 같이 자료구조를 짰다. => queue<pair<TreeNode*, int>> q;

second 위치에 dir변수를 두어서

dir==-1일 경우 거꾸로 저장하도록 했다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        if(root==NULL){
            return ans;
        }
        vector<int> v;
        queue<pair<TreeNode*int>> q;
        q.push(make_pair(root, 1));
        
        while(!q.empty()){
           int size = q.size();
            int dir;
            
            for(int i=0; i<size; i++){
                TreeNode* node = q.front().first;
                dir = q.front().second;
                
                v.push_back(node->val);
                q.pop();
                
                if(node->left!=NULL){
                    q.push(make_pair(node->left, -dir));
                }
                
                if(node->right!=NULL){
                    q.push(make_pair(node->right, -dir));
                }
            }
            
            if(dir==-1){
                vector<int> temp;
                for(int i=v.size()-1; i>=0; i--){
                    temp.push_back(v[i]);
                }
                ans.push_back(temp);                
            }else{
                ans.push_back(v);
            }
 
            v.clear();
        }
        
        return ans; 
    }
};
cs
반응형

'Algorithm > LeetCode' 카테고리의 다른 글

LeedCode : 40. Combination Sum II  (0) 2021.01.03
LeetCode : 39. Combination Sum  (0) 2021.01.03
LeetCode : 102. Binary Tree Level Order Traversal  (0) 2021.01.01
LeetCode : 101. Symmetric Tree  (0) 2021.01.01
LeetCode : 100. Same Tree  (0) 2020.12.31
Comments