博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
U面经Prepare: Print Binary Tree With No Two Nodes Share The Same Column
阅读量:7003 次
发布时间:2019-06-27

本文共 1662 字,大约阅读时间需要 5 分钟。

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 List
print(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 }

 

转载地址:http://qzytl.baihongyu.com/

你可能感兴趣的文章
批处理切换当前目录的做法
查看>>
微信公众平台开发(43)火车时刻查询
查看>>
NetBeans 时事通讯(刊号 # 148 - May 28, 2011)
查看>>
C# ListView控件的间隔色和自动适应宽度
查看>>
MPTCP 理解
查看>>
day1 简介,变量,用户输入,字符串拼接,列表,元组,字典
查看>>
简单计算器的面向过程实现和面向对象实现对比 分类: C# ...