Given a binary tree, print it vertically. The following example extends strates vertical order traversal.
1
/\
2 3
/\/\
4 5 6 7
\\
8 9
The output of print this tree vertically will be:
4
2
1 5 6
3 8
7
9
From geeksforgeeks: http://www.geeksforgeeks.org/print-binary-tree-vertical-order/
Vertical access means that each column is assigned a column number. The left child is equal to 1 by the root column number, and the right child is equal to the root one by 1. print the same row with the same column number.
So the most direct method is to first find out the number of columns. Print each column and traverse the tree, as long as the column number is equal to it. The time complexity is equal to the number of columns * tree traversal. The worst case is O (n ^ 2 ).
If two nodes have the same Horizontal Distance (HD), then they are on same vertical line.
A simpler method is to directly use a hashmap. The key is the column number, and the value is the number of all the same columns. Traverse the tree and fill in the hashmap, then we can print all the numbers in a column by traversing a hashmap.
Variant
Print Nodes in Top View of Binary Tree
Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. given a binary tree, print the top view of it. the output nodes can be printed in any order. expected time complexity is O (n)
A node x is there in output if x is the topmost node at its horizontal distance. horizontal distance of a child of a node x is equal to horizontal distance of x minus 1, and that of right child is horizontal distance of x plus 1.
1
/\
2 3
/\/\
4 5 6 7
Top view of the above binary tree is
4 2 1 3 7
1
/\
2 3
\
4
\
5
\
6
Top view of the above binary tree is
2 1 3 6
Similarly, the first number of columns is printed. Because it can print in any order, hashset is used to record whether it exists. If it does not exist, it can be printed and added to hashset.
From: http://www.geeksforgeeks.org/print-nodes-top-view-binary-tree/
Print a Binary Tree in Vertical Order