Leetcode/NeetCode

[BinaryTree][Medium] 102. Binary Tree Level Order Traversal

자전거통학 2024. 7. 18. 20:30

https://leetcode.com/problems/binary-tree-level-order-traversal/description/

 

주어진 binary tree를 level order 탐색하라.

 

사실상 easy 난이도 문제.

BS의 기본 문제, 다른 문제들로 응용에 잘 나옴. 

 

코드 

더보기
vector<vector<int>> levelOrder(TreeNode* root) 
{
    vector<vector<int>> vRet;
    if (root == nullptr)
        return vRet;

    queue<TreeNode*> qBuff;
    qBuff.push(root);
    while (qBuff.size() > 0)
    {
        vector<int> vBuff;
        int cnt = qBuff.size();
        for (int q = 0; q < cnt; ++q)
        {
            TreeNode* node = qBuff.front();
            qBuff.pop();
            vBuff.push_back(node->val);

            if (node->left != nullptr)	qBuff.push(node->left);
            if (node->right != nullptr)	qBuff.push(node->right);
        }
        vRet.push_back(vBuff);
    }
    return vRet;
}

 

 

결과