http://www.geeksforgeeks.org/print-binary-tree-vertical-order/
1 Packagealgorithms;2 3 Importjava.util.ArrayList;4 Importjava.util.List;5 ImportJava.util.Map;6 ImportJava.util.TreeMap;7 8 Public classprintvertical {9 Ten Private StaticTreemap<integer, list<treenode>> HM =NewTreemap<>(); One A Public Static voidMain (string[] args) { -TreeNode root =NewTreeNode (1); -TreeNodeNewTreeNode (2); theTreeNode three =NewTreeNode (3); -TreeNode four =NewTreeNode (4); -TreeNode five =NewTreeNode (5); -TreeNode six =NewTreeNode (6); +TreeNode seven =NewTreeNode (7); -TreeNode eight =NewTreeNode (8); +TreeNode Nine =NewTreeNode (9); ARoot.left =both ; atRoot.right =three; -Two.left =Four ; -Two.right =five; -Three.left =six; -Three.right =Seven; -Six.right =Eight; inSeven.right =Nine; - printvertical (root); to for(Map.entry<integer, list<treenode>>Entry:hm.entrySet ()) { +System.out.println ("key=====" +Entry.getkey ()); -list<treenode> temp =Entry.getvalue (); the for(TreeNode node:temp) { *System.out.println ("Node val======" +node.val); $ }Panax Notoginseng } - } the + Public Static voidprintvertical (TreeNode root) { AHelper (0, root); the } + - Public Static voidHelperintcur, TreeNode root) { $ if(Root = =NULL) $ return; - -Arraylist<treenode>Array; the if(Hm.containskey (cur)) { -Array = (arraylist<treenode>) hm.get (cur);Wuyi}Else { theArray =NewArraylist<treenode>(); - } Wu Array.add (root); - hm.put (cur, array); AboutHelper (cur-1, root.left); $Helper (cur + 1, root.right); - } -}
< note > It is important to use TREEMAP instead of HashMap to save the data that is traversed. Better to use TreeMap in this case, as it would store the result in ascending order,
Which we is interested in.
Print a Binary Tree in Vertical Order