Binary Tree Level Order Traversal

code


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> ret;
        if(root == NULL)
        {
            return ret;
        }

        list<TreeNode*> queue;
        queue.push_back(root);

        while(!queue.empty())
        {
            int size = queue.size();
            vector<int> vecTemp;
            for(int i = 0; i<size; i++)
            {
                TreeNode* p = queue.front();
                queue.pop_front();
                vecTemp.push_back(p->val);

                if(p->left != NULL)
                {
                    queue.push_back(p->left);
                }

                if(p->right != NULL)
                {
                    queue.push_back(p->right);
                }
            }
            ret.push_back(vecTemp);
        }

        return ret;
    }
};

results matching ""

    No results matching ""