궁금한게 많은 개발자 노트

[ leetcode ] 102. Binary Tree Level Order Traversal 본문

Algorithm

[ leetcode ] 102. Binary Tree Level Order Traversal

궁금한게 많은 개발자 2023. 5. 2. 13:19

Binary Tree가 주어졌을 때, level order로 순회하는 순서를 반환하는 문제입니다.

BFS(Breadth-First-Search)로 접근하여 최상위 노드부터 넣고 자식들을 순서대로 넣으면서 level order로 순회합니다.

/**
 * 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) {}
 * };
 */
#include <algorithm>
#include <queue>

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
    	if (root) tree_queue.push(root);
        vector<vector<int>> answer;
        queue<TreeNode*> tree_queue;
        
        while (!tree_queue.empty()) {
			vector<int> level;
            int size = tree_queue.size();
            for (int i = 0; i < size; i++) {
            	TreeNode* current = tree_queue.front();
                tree_queue.pop();
                level.push_back(current->val);
                if (current->left) tree_queue.push(current->left);
                if (current->right) tree_queue.push(current->right);
            }
            answer.push_back(level);
		}
        return answer;
    }
};
Comments