Print a Binary Tree Vertical Order (column wise)

This is a Facebook interview question.

We have a binary tree, suppose like this:

8/   \
    610/ \   /  \
  47912/ \
35

We have to print this binary tree in top-down manner - column wise. Note that, 8, 7 & 9 would be considered in same column. So the required output should be:

34658791012
public void traverse(Node root) {
    TreeMap<Integer, List<Integer>> columnMap = new TreeMap<>();

    recurseTraverse(root, columnMap, 0);

    for (Entry<Integer, List<Node<Integer>>> entry: columnMap.entrySet()) {
        System.out.println("Column - " + entry.getKey() + " : " + entry.getValue());
    }
}

private void recurseTraverse(final Node node, final Map<Integer, List<Integer>> columnmap, final int column) {
    if (node == null) {
        return;
    }
    List<Integer> list = columnmap.get(column);
    if (list == null) {
        list = new ArrayList<Integer>();
        columnmap.put(column, list);
    }
    list.add(node.getValue());
    recurse(node.left(), columnmap, column - 1);
    recurse(node.right(), columnmap, column + 1);

}

From:

http://codereview.stackexchange.com/questions/36799/printing-a-binary-tree-top-down-column-wise

你可能感兴趣的:(binary)