【剑指offer】【树】32-II.从上到下打印二叉树

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

队列(BFS)

与I类似,要按层打印,所以每次先获取队列的长度,这个长度即为该层元素的个数,然后将其保存到数组中,依次将其左右节点压入队列;
时间复杂度:O(N)
空间复杂度:O(N)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        if(!root) return {};
        vector<vector<int>> res;
        queue<TreeNode *> q;
        q.push(root);
        while(!q.empty())
        {
            int n = q.size();
            vector<int> line;
            for(int i = 0; i < n; i++)
            {
                auto tmp = q.front();
                q.pop();
                line.push_back(tmp -> val);

                if(tmp -> left) q.push(tmp -> left);
                if(tmp -> right) q.push(tmp -> right);
            }
            res.push_back(line);
        }
        return res;
    }
};
posted @ 2020-04-09 21:09  NaughtyCoder  阅读(93)  评论(0)    收藏  举报