剑指 Offer 32 - I. 从上到下打印二叉树

时间:2021-01-30 12:09:44   收藏:0   阅读:0

题意

从上到下打印二叉树的每一行,最后返回一个层序遍历的序列

思路

代码

class Solution {
public:
    vector<int> levelOrder(TreeNode* root) {
        if(!root) {
            return {};
        }
        queue<TreeNode*> q;
        vector<int> ans;
        q.push(root);
        while(!q.empty()) {
            auto cur = q.front();
            q.pop();
            ans.emplace_back(cur->val);
            if(cur->left) {
                q.push(cur->left);
            }
            if(cur->right) {
                q.push(cur->right);
            }
        }       
        return ans;
    }
};
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!