Print a Binary Tree in Vertical Order

Given a binary tree, print it vertically. The following example illustrates 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/

这里垂直访问的意思是,每一列给它一个列号,左孩子比根的列号减1,右孩子比根的加1.列号相同的打印在同一行。

所以最直接的方法是,先把列数找出来。然后每一列打印,遍历树就行,只要列号等于它就打印出来。时间复杂度等于列数*树遍历,最坏情况就是O(n^2)。

If two nodes have the same Horizontal Distance (HD), then they are on same vertical line.

更简单的方法是,直接用一个hashmap,key是列号,value就是所有同一列的数,遍历一次树填好hashmap,然后就可以遍历一次hashmap把所有数按列打印出来。

变种

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

同样,只是把每一列第一个数打印出来。因为可以print in any order,所以用hashset来记录是否存在,如果不存在就可以打印了,并加入到hashset中。

from: http://www.geeksforgeeks.org/print-nodes-top-view-binary-tree/

posted @ 2014-11-08 18:43  linyx  阅读(425)  评论(0编辑  收藏  举报