层次遍历,借助一个队列
/**
* 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<int> levelOrder(TreeNode* root) {
if(root==nullptr) return {};
queue<TreeNode*>q;
q.push(root);
vector<int>res;
while(!q.empty()){
TreeNode*temp=q.front();
res.push_back(temp->val);
q.pop();
if(temp->left!=nullptr) q.push(temp->left);
if(temp->right!=nullptr) q.push(temp->right);
}
return res;
}
};