102. Binary Tree Level Order Traversal

Problem:

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

For example:
Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
</p>

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]
</p>

Solutions:

/**
 * 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) {
        vector<vector<int>> ret;
        if (root == NULL)   return ret;

        queue<TreeNode*> q;
        q.push(root);

        while (!q.empty()) {
            int count = 0;
            vector<int> level;
            for (int i = q.size() - 1; i >= 0; --i) {  // starting from 0 is wrong because q.size() keeps on changing. 
                auto node = q.front(); q.pop();
                level.push_back(node->val);
                if (node->left) {
                    q.push(node->left);
                }

                if (node->right) {
                    q.push(node->right);
                }
            }

            ret.push_back(level);
        }

        return ret;

    }
};

results matching ""

    No results matching ""