第四届Java高职高专组决赛——横向打印二叉树

来源:互联网 发布:数据分析 太原培训 编辑:程序博客网 时间:2024/05/28 05:14


标题:横向打印二叉树


    二叉树可以用于排序。其原理很简单:对于一个排序二叉树添加新节点时,先与根节点比较,若小则交给左子树继续处理,否则交给右子树。


    当遇到空子树时,则把该节点放入那个位置。 


    比如,10 8 5 7 12 4 的输入顺序,应该建成二叉树如图1所示。 


    本题目要求:根据已知的数字,建立排序二叉树,并在标准输出中横向打印该二叉树。 


    输入数据为一行空格分开的N个整数。 N<100,每个数字不超过10000。
    输入数据中没有重复的数字。 


    输出该排序二叉树的横向表示。 对应上例中的数据,应输出:


   |-12
10-|
   |-8-|
       |   |-7
       |-5-|
           |-4




    为了便于评卷程序比对空格的数目,请把空格用句点代替:
...|-12
10-|
...|-8-|
.......|...|-7
.......|-5-|
...........|-4


例如:
用户输入:
10 5 20
则程序输出:
...|-20
10-|
...|-5


再例如:
用户输入:
5 10 20 8 4 7
则程序输出:
.......|-20
..|-10-|
..|....|-8-|
..|........|-7
5-|
..|-4




资源约定:
峰值内存消耗(含虚拟机) < 64M

CPU消耗  < 1000ms



public class Test4 {public static void main(String[] args) {int[] n = {34,32,35,47,23,35,41,14,12,15,7,10,8,5,12,7,3,6};Node root = new Node(n[0]);root.s =root.e+"-|"; for (int i = 1; i < n.length; i++) {Node node = new Node(n[i]);if(node.e>root.e){//子节点比父节点大addRight(node,root,0);}else{//子节点比父节点小addLeft(node,root,0);}}print(root);}//总是先输出右节点,然后输出他,最后输出左节点private static void print(Node root) {if(root.right!=null){print(root.right);}//如果他没有子节点,那么就去掉尾部的"-|"if(root.left==null&&root.right==null){System.out.println(root.s.substring(0,root.s.length()-2));}else{System.out.println(root.s);}if(root.left!=null){print(root.left);}}private static void addRight(Node node, Node root,int n) {//如果父节点的右节点为空,则直接添加到右节点上if(root.right==null){//将父节点的数字和“-”,换成".",然后再接上子节点//node.s = root.s.replaceAll("[0-9]", ".").replaceAll("-", ".")+"-"+node.e+"-|";if(n==0){//node.s = root.s.replaceAll("[0-9]", ".").replaceAll("-", ".").substring(0, root.s.length()-1).replace('|', '.')+"|-"+node.e+"-|";node.s = root.s.replaceAll("[0-9]", ".").replaceAll("-", ".").substring(0, root.s.length()-1);int index = node.s.lastIndexOf('|');if(index!=-1){node.s = node.s.substring(0,index)+"."+node.s.substring(index+1);}node.s = node.s+"|-"+node.e+"-|";}else{node.s = root.s.replaceAll("[0-9]", ".").replaceAll("-", ".")+"-"+node.e+"-|";}root.right = node;return;}if(node.e>root.right.e){addRight(node, root.right,0);}else{addLeft(node, root.right,1);}}private static void addLeft(Node node, Node root,int n) {//如果父节点的左节点为空,则直接添加到左节点上if(root.left==null){//将父节点的数字和“-”,换成".",然后再接上子节点//node.s = root.s.replaceAll("[0-9]", ".").replaceAll("-", ".")+"-"+node.e+"-|";if(n==0){node.s = root.s.replaceAll("[0-9]", ".").replaceAll("-", ".").substring(0, root.s.length()-1);int index = node.s.lastIndexOf('|');if(index!=-1){node.s = node.s.substring(0,index)+"."+node.s.substring(index+1);}node.s = node.s+"|-"+node.e+"-|";}else{node.s = root.s.replaceAll("[0-9]", ".").replaceAll("-", ".")+"-"+node.e+"-|";}root.left = node;return;}if(node.e>root.left.e){addRight(node, root.left,1);}else{addLeft(node, root.left,0);}}}class Node{int e;Node left;Node right;String s;public Node(int e) {this.e = e;}}






原创粉丝点击