Skip to content

Instantly share code, notes, and snippets.

@manojnaidu619
Created August 8, 2019 04:58
Show Gist options
  • Save manojnaidu619/0c92e8610ed8982cb7018e3d5dcc3b1f to your computer and use it in GitHub Desktop.
Save manojnaidu619/0c92e8610ed8982cb7018e3d5dcc3b1f to your computer and use it in GitHub Desktop.
BFS / Level order Traversal in CPP
queue<TreeNode*> q; // To store the node addresses
vector<int> result; // To store the values in the node
result.push_back(root->val);
q.push(root);
while (!q.empty()) {
node = q.front();
q.pop();
if(node->left){
result.push_back(node->left->val);
q.push(node->left);
}else{
result.push_back(NULL);
}
if(node->right){
result.push_back(node->right->val);
q.push(node->right);
}else{
result.push_back(NULL);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment