using queue to implement level order traversal of binary tree


  • 0
    1
    vector<vector<int>> levelOrder(TreeNode* root) {
            vector<vector<int> > result;
            if (root == NULL)    // deal with when root is NULL
                return result;
            int front = 0, rear = -1, level = 1;
            vector<TreeNode*> vtmp;         //using vector to implement queue
            vtmp.push_back(root);
            rear++;
            while ( rear >= front) {
                TreeNode* node;
                int tmp = rear;
                result.resize(level);
                // result[level-1]
                while (front <= tmp) {
                    node = vtmp[front++];
                    if (node->left != NULL) {
                        vtmp.push_back(node->left);
                        rear++;
                    }
                    if (node->right != NULL) {
                        vtmp.push_back(node->right);
                        rear++;
                    }
                    result[level-1].push_back(node->val);
                }
                level++;
            }
            return result;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.