题目

题解

其实就是二叉树的层次遍历,比102简单。因为这道题不分层因此用dfs不好做,还是用bfs好

  • 时间复杂度$O(n)$
  • 空间复杂度$O(n)$
class Solution {
public:
    vector<int> levelOrder(TreeNode* root) {
        vector<int> res;
        if(!root) return res;
        queue<TreeNode*> q({root});
        while(!q.empty()){
            auto tmp = q.front();q.pop();
            res.push_back(tmp->val);
            if(tmp->left) q.push(tmp->left);
            if(tmp->right) q.push(tmp->right);
        }
        return res;
    }
};