## Bloomberg LP Interview Question for Python Developers

Country: United States

Comment hidden because of low score. Click to expand.
0
of 0 vote

Straightforward level order traversal using a queue. Solution in Python below.

``````from collections import deque
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None

def level_order(root):
q = deque([root])
while q:
currLevel = []
qSize = len(q)
for _ in range(qSize):
curr = q.popleft()
currLevel.append(curr.val)
if curr.left: q.append(curr.left)
if curr.right: q.append(curr.right)
print(currLevel)

'''
Construct the following tree
1
/   \
2    3
/
4
/
5
'''

one_node = Node(1)
two_node = Node(2)
three_node = Node(3)
four_node = Node(4)
five_node = Node(5)

one_node.left = two_node
one_node.right = three_node
two_node.left = four_node
four_node.left = five_node

level_order(one_node)``````

Output:

``````[1]
[2, 3]
[4]
[5]``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````struct Node {
Node(int x): data(x), left(NULL), right(NULL) {}
int data;
Node *left;
Node *right;
};

void LevelOrder(Node *root) {
if (root == NULL) return;
queue<Node*> q;
q.push(root);
q.push(NULL);
Node *curr;

while(q.size() > 1) {
curr = q.front();
q.pop();
if (curr == NULL) {
// New level
q.push(NULL);
cout << endl;
} else {
if(curr->left) q.push(curr->left);
if(curr->right) q.push(curr->right);
cout << curr->data << " ";
}
}
}``````

Output:

1
2 3
4 5 6 7

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.