Print binary tree from top to bottom-2

Likou Address

Use the queue, before starting to join the queue, determine the current queue length as the number of nodes that need to be printed next

/**
 * 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) {
        std::deque<TreeNode*> q;
        if (root) q.push_back(root);
        vector<vector<int>> res;
        while (!q.empty()) {
            int len = q.size();
            vector<int> row;
            for (int i = 0; i < len; ++i) {
                root = q.front();
                q.pop_front();
                row.push_back(root->val);
                if (root->left) q.push_back(root->left);
                if (root->right) q.push_back(root->right);
            }
            res.push_back(row);
        }
        return res;
    }
};

 

Guess you like

Origin blog.csdn.net/TESE_yan/article/details/114296324