Print a Binary Tree in Vertical Order

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.