Domanda di colloquio di Meta

Given a binary tree, print the nodes level by level

Risposte di colloquio

Anonimo

16 giu 2010

bfs

Anonimo

29 dic 2010

public void printBST(BinarySearchTree tree) { Node root = tree.getRoot(); Map depthMap; depthMap.put(root, 0); List toVisit; toVisit.add(root); int currLevel = 0; while(toVisit.isEmpty() == false) { Node n = toVisit.remove(0); if(currLevel != depthMap.get(n)) { System.out.println(); currLevel = depthMap.get(n); } System.out.print(n.getValue() + " "); if(n.hasLeft()) { depthMap.put(n.getLeft(), depthMap.get(n.getLeft()) + 1); toVisit.add(n.getLeft()); } if(n.hasRight()) { depthMap.put(n.getRight(), depthMap.get(n.getRight()) + 1); toVisit.add(n.getRight()); } } }

Anonimo

18 nov 2010

Here is my contribution in C. void printLevelInWidth(node root){ int levelExists = 1; int level = 1; while (levelExists){ levelExists = printLevel(root, level); } } int printLevel(node root, level){ if (root == NULL) return 0; if (level > 1) { return printLevel(root->leftChild, level-1) || printLevel(root->rightChild, level-1); } printf("%d", root->value); return 1; }