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]

- prudent_programmer June 17, 2019 | Flag Reply
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

- Jonathan James September 23, 2019 | Flag Reply


Add a Comment
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.

Learn More

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.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More