짱아의 개발 기록장

LeetCode : 107. Binary Tree Level Order Traversal II 본문

Algorithm/LeetCode

LeetCode : 107. Binary Tree Level Order Traversal II

jungahshin 2021. 1. 8. 11:32
반응형

처음 queue를 사용해서 문제를 풀었을 때는, 시간이 faster than 13.36%가 나와서,,,, 큰일났다 싶었다.

따라서, 다른 분들의 풀이를 참고해서 큐를 사용하지 않고 그냥 dfs로도 풀어보았다.

 

1. runtime -> faster than 13.36%, memory -> less than 62.96%

 

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
class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        queue<TreeNode*> q;
        q.push(root);
        vector<vector<int>> ans;
        stack<vector<int>> st;
        
        while(!q.empty()){
            int size = q.size();
            vector<int> v;
            for(int i=0; i<size; i++){
                TreeNode* node = q.front();
                q.pop();
                
                if(node==NULLcontinue;
                v.push_back(node->val);
                
                q.push(node->left);
                q.push(node->right);
            }
            
            if(v.size()==0continue;
            st.push(v);
        }
        
        while(!st.empty()){
            ans.push_back(st.top());
            st.pop();
        }
        
        return ans;
    }
};
cs

 

2. runtime -> faster than 42.85%, memory -> less than 11.01%

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
    void Traversal(vector<vector<int>> &ans, TreeNode* node, int level){
        if(node==NULL){
            return;
        }

// 새로운 level에 도달했을 때 새로운 배열을 생성해서 넣어준다.
        if(level==ans.size()){
            ans.push_back({});
        }
        
        ans[level].push_back(node->val);
        Traversal(ans, node->left, level+1);
        Traversal(ans, node->right, level+1);
    }
    
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> ans;
        Traversal(ans, root, 0);
        reverse(ans.begin(), ans.end());
        
        return ans;
    }
};
cs
반응형

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

LeetCode : 16. 3Sum Closest  (0) 2021.01.12
LeetCode : 15. 3Sum  (0) 2021.01.11
LeetCode : 14. Longest Common Prefix  (0) 2021.01.07
LeetCode : 104. Maximum Depth of Binary Tree  (0) 2021.01.06
LeetCode : 53. Maximum Subarray  (0) 2021.01.04
Comments