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

Tag: 剑指-Offer Posted on 2022-02-28 11:58:15 Edited on 2022-02-28 12:05:30 Views: 145

概述

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/