使用队列维护,时间复杂度O(n),可解决右视图问题
vector<int> level(TreeNode* root) {
if(root == NULL) return {};
vector<int> ans;
queue<TreeNode*> q;
q.push_back(root);
while(!q.empty()) {
int len = q.size();
for(int i=0; i<len; i++) {
TreeNode* cur = q.front();
q.pop();
ans.push_back(cur->val);
if(root->left != NULL) q.push(root->left);
if(root->right != NULL) q.push(root->right);
}
return ans;
}