Bloomberg L.P.

  www.bloomberg.com
  www.bloomberg.com

Interview Question

Financial Software Developer Interview(Student Candidate) New York, NY

gave me a tree of 3 level and provided me a number that

  contains the level number and asked me to code a program that would print the nodes on that level in the tree.
Tags:
binary tree
Answer

Interview Answer

3 Answers

0

Recursion

Interview Candidate on Feb 19, 2014
0

BFS

Anonymous on Sep 30, 2014
0

possible BFS solution in Java:

public void printLevel(Node root, int level) {
    HashMap<Node, Integer> dist = new HashMap<Node, Integer>();
    Deque<Node> nodes = new ArrayDeque<Node>();
    dist.put(root, 1);
    nodes.offer(root);

    while (nodes.size() > 0) {
        Node curr = nodes.poll();
        if (dist.get(curr) == level) {
           System.out.println(curr);
           continue;
         } else {
            if (curr.left != null) {
            dist.put(curr.left, dist.get(curr) + 1);
            nodes.offer(curr.left);
         }
         if (curr.right != null) {
               dist.put(curr.right, dist.get(curr) + 1);
               nodes.offer(curr.right);
         }
      }
   }
}

Anonymous on Sep 30, 2014

Add Answers or Comments

To comment on this, Sign In or Sign Up.