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

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。

标签:剑指 Offer发布于:编辑于:浏览量:1632

概述

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;
    }
};