Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
930 B
0
Indexable
Never
/**
 * 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:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>>res;
        if(!root) return res;
        queue<TreeNode*>s;
        s.push(root);
        while(!s.empty()){
            int se=s.size();
            vector<int>ans;
            while(se--){
                TreeNode* tmp=s.front(); s.pop();
                ans.push_back(tmp->val);
                if(tmp->left) s.push(tmp->left);
                if(tmp->right) s.push(tmp->right);
            }
            res.push_back(ans);
        }
        return res;
    }
};
Leave a Comment