Microsoft interview question

Data structures - - Write program to print Binary Tree using bredth first search and depth first search

Interview Answer

Anonymous

6 Nov 2012

C++ _____________________________________________ #include #include "math.h" #include #include using namespace std; class BST { public: BST::BST(int v) : value(v) { left = NULL; right = NULL; } BST *left; BST *right; int value; }; void bfs_print(BST *root) { vector queue; queue.push_back(root); while(queue.size() > 0) { BST *temp = queue.front(); queue.erase(queue.begin()); // Print it cout value; if(temp->left != NULL) queue.push_back(temp->left); if(temp->right != NULL) queue.push_back(temp->right); } } void dfs_print(BST *root) { if(root->left != NULL) dfs_print(root->left); // Print it cout value; if(root->right != NULL) dfs_print(root->right); } int main() { BST root(8); BST root5(5); BST root10(10); BST root1(1); BST root6(6); BST root9(9); BST root12(12); BST root13(13); root.left = &root5; root.right = &root10; root5.left = &root1; root5.right = &root6; root10.left = &root9; root10.right = &root12; root12.right = &root13; bfs_print(&root); dfs_print(&root); return 0; }