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

Tag: 剑指-Offer Posted on 2022-02-25 21:16:14 Edited on 2022-02-28 12:02:40 Views: 157

概述

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

https://leetcode.com/problems/binary-tree-level-order-traversal/

层次遍历

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

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