Skip to content

Instantly share code, notes, and snippets.

@sourabh2k15
Created January 6, 2018 05:11
Show Gist options
  • Select an option

  • Save sourabh2k15/b74b4f9aaacb50a1668ca61656bfe51e to your computer and use it in GitHub Desktop.

Select an option

Save sourabh2k15/b74b4f9aaacb50a1668ca61656bfe51e to your computer and use it in GitHub Desktop.
void levelOrder(TreeNode* root) {
queue<TreeNode*> bfs;
bfs.push(root);
while(!bfs.empty()){
TreeNode* current = bfs.front(); bfs.pop();
if(current){
cout << current->val << " ";
bfs.push(current->left);
bfs.push(current->right);
}
}
cout << endl;
}
@vinaybedre

vinaybedre commented May 1, 2020

Copy link
Copy Markdown

With the above approach, we will end up pushing some unwanted nulls on to the queue. (i am not sure how queue works in CPP)
If before pushing on to the stack if we can check
if(current->left) bfs.push(current.left)
we could avoid unwanted pushing of nulls and reduce number of time loops runs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment