Give a binary tree, elegantly print it so that no two tree nodes share the same column. Requirement: left child should appear on the left column of root, and right child should appear on the right of root.Example: a b c d e fz g h i j
这道题若能发现inorder traversal each node的顺序其实就是column number递增的顺序,那么就成功了一大半
维护一个global variable,colNum, 做inorder traversal
然后level order 一层一层打印出来
1 package uberOnsite; 2 3 import java.util.*; 4 5 public class PrintTree { 6 public static class TreeNode { 7 char val; 8 int col; 9 TreeNode left;10 TreeNode right;11 public TreeNode(char value) {12 this.val = value;13 }14 }15 16 static int colNum = 0;17 18 public static Listprint(TreeNode root) {19 List res = new ArrayList ();20 if (root == null) return res;21 inorder(root);22 levelOrder(root, res);23 return res;24 }25 26 public static void inorder(TreeNode node) {27 if (node == null) return;28 inorder(node.left);29 node.col = colNum;30 colNum++;31 inorder(node.right);32 33 }34 35 public static void levelOrder(TreeNode node, List res) {36 Queue queue = new LinkedList ();37 queue.offer(node);38 while (!queue.isEmpty()) {39 StringBuilder line = new StringBuilder();40 HashMap lineMap = new HashMap ();41 int maxCol = Integer.MIN_VALUE;42 int size = queue.size();43 for (int i=0; i res = print(A);90 for (String each : res) {91 System.out.println(each);92 }93 }94 95 }