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

标签: 剑指 Offer 发布于:2022-02-28 11:58:15 编辑于:2022-02-28 12:05:30 浏览量:970

概述

https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/

层序遍历

class Solution {
public:
    vector<int> levelOrder(TreeNode* root) {
        vector<int> ans;
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            int sz = q.size();
            while (sz > 0) {
                sz --;
                auto n = q.front(); q.pop();
                if (n) {
                    ans.push_back(n->val);
                    q.push(n->left);
                    q.push(n->right);
                }
            }
        }
        return ans;
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/