102. Binary Tree Level Order Traversal

/**
 * 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) {
        queue<TreeNode*> toVisit;
        if (root) toVisit.push(root);
        vector<vector<int>> res;
        while (!toVisit.empty()) {
            vector<int> currlev;
            for (int i = toVisit.size(); i > 0; i--) {
                TreeNode* tmp = toVisit.front();
                toVisit.pop();
                currlev.push_back(tmp->val);
                if (tmp->left) toVisit.push(tmp->left);
                if (tmp->right) toVisit.push(tmp->right);
            }
            res.push_back(currlev);
        }
        return res;
    }
};

results matching ""

    No results matching ""