Print a Binary Tree in Vertical Order

http://www.geeksforgeeks.org/print-binary-tree-vertical-order/

 1 package algorithms;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 import java.util.Map;
 6 import java.util.TreeMap;
 7 
 8 public class PrintVertical {
 9 
10     private static TreeMap<Integer, List<TreeNode>> hm = new TreeMap<>();
11     
12     public static void main(String[] args) {
13         TreeNode root = new TreeNode(1);
14         TreeNode two = new TreeNode(2);
15         TreeNode three = new TreeNode(3);
16         TreeNode four = new TreeNode(4);
17         TreeNode five = new TreeNode(5);
18         TreeNode six = new TreeNode(6);
19         TreeNode seven = new TreeNode(7);
20         TreeNode eight = new TreeNode(8);
21         TreeNode nine = new TreeNode(9);
22         root.left = two;
23         root.right = three;
24         two.left = four;
25         two.right = five;
26         three.left = six;
27         three.right = seven;
28         six.right = eight;
29         seven.right = nine;
30         printVertical(root);
31         for(Map.Entry<Integer, List<TreeNode>> entry: hm.entrySet()) {
32             System.out.println("key====="+entry.getKey());
33             List<TreeNode> temp = entry.getValue();
34             for(TreeNode node: temp){
35                 System.out.println("node val======"+node.val);
36             }
37         }
38     }
39     
40     public static void printVertical(TreeNode root) {
41         helper(0, root);
42     }
43     
44     public static void helper(int cur, TreeNode root) {
45         if(root == null)
46             return;
47 
48         ArrayList<TreeNode> array;
49         if(hm.containsKey(cur)) {
50             array = (ArrayList<TreeNode>) hm.get(cur);
51         } else {
52             array = new ArrayList<TreeNode>();
53         }
54         array.add(root);
55         hm.put(cur, array);
56         helper(cur - 1, root.left);
57         helper(cur + 1, root.right);
58     }
59 }

<注> 需要注意的是使用TreeMap而不是HashMap来存遍历以后的数据。Better to use TreeMap in this case, as it will store the result in ascending order, 

    which we are interested in.

posted @ 2015-11-30 06:54  Phoebe815  阅读(381)  评论(0编辑  收藏  举报