HackerRank Day 23 BST Level order traversal 30 days of code solution YASH PAL, 31 July 2024 In this HackerRank Day 23 BST Level order traversal 30 days of code problem set, we need to complete a levelorder function that can accept a root node as an input and then print the level order traversal of the binary search tree. Problem solution in Python 2 programming. def levelOrder(self,root): #Write your code here s = '' if (root != None): q = [root] while (len(q) != 0): s += str(q[0].data) + ' ' if (q[0].left != None): q.append(q[0].left) if (q[0].right != None): q.append(q[0].right) q.pop(0) print s Problem solution in Python 3 programming. def levelOrder(self,root): if root is None: return qu = [] qu.append(root) while len(qu) !=0: p = qu.pop(0) print(p.data, end=' ') if p.left is not None: qu.append(p.left) if p.right is not None: qu.append(p.right) Problem solution in java programming. static LinkedList<Integer> queue = new LinkedList(); static void levelOrder(Node root){ LinkedList<Node> treeQueue = new LinkedList(); treeQueue.add(root); while(treeQueue.peek() != null) { Node toprint = treeQueue.remove(); System.out.print(toprint.data); if(toprint.left != null) { treeQueue.add(toprint.left); } if(toprint.right != null) { treeQueue.add(toprint.right); } if(treeQueue.peek() != null) { System.out.print(" "); } } } Problem solution in c++ programming. void levelOrder(Node * root){ std::queue<Node*> q; Node* c; if (root != NULL) { q.push(root); } while (!q.empty()) { c = q.front(); q.pop(); cout << c->data << " "; if (c->left!=NULL) q.push(c->left); if (c->right!=NULL) q.push(c->right); } } Problem solution in c programming. #define max(a, b) (a > b ? a : b) int getHeight(Node *root) { if (root == NULL) return 0; else return 1 + max(getHeight(root->left), getHeight(root->right)); } void printGivenLevel(Node *root, int level) { if (root == NULL) return; if (level == 1) printf("%d ", root->data); else if (level > 1) { printGivenLevel(root->left, level-1); printGivenLevel(root->right, level-1); } } void levelOrder(Node* root){ //Write your code here int height = getHeight(root); int i; for (i = 1; i <= height; i++) { printGivenLevel(root, i); } } Problem solution in Javascript programming. var queue = [root]; while (queue.length > 0) { var node = queue.shift(); write(node.data + " "); if(node.left) { queue.push(node.left); } if (node.right) { queue.push(node.right); } } function write(str){ process.stdout.write(str); } 30 days of code coding problems