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

[leetcode 102] Binary Tree Level Order Traversal

by m2162003 2020. 10. 3.

 

같은 레벨의 노드끼리 배열을 만들어 return한다.

 

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],

return its level order traversal as:

[ [3], [9,20], [15,7] ]

 

풀이

- 큐와 bfs를 이용하여 레벨 별로 노드를 저장한다.

/**
 * 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:
    
    void Traverse(TreeNode* root,  vector<vector<int>> &answer){
        queue<pair<TreeNode*, int>> q;
        q.push(make_pair(root, 0));
               
        while(!q.empty()){
            
            TreeNode* cur = q.front().first;
            int level = q.front().second;
            
            q.pop();
          
            if(cur != nullptr){
                
                if(answer.size() < level+1){
                    vector<int> v = {cur->val};
                    answer.push_back(v);
                }else {
                    answer[level].push_back(cur->val);
                }
                 q.push(make_pair(cur->left, level+1));
                 q.push(make_pair(cur->right, level+1));
            }      
        }
    }
    
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> answer;        
        Traverse(root, answer);
        return answer;
    }
};

댓글