试题 历届试题 横向打印二叉树

在这里插入图片描述

import java.util.Scanner;
public class Main{
public static int root;
public static point[] tree = new point[10005];
static class point{
public int value;//自身节点编号
public int father;//父母节点编号
public int left;//左孩子节点编号
public int right;//右孩子节点编号

public point (){
this.value=0;
this.father=0;
this.left=0;
this.right=0;
}
}
public void dfs(int start,string s,int n,string s1){
if(tree[start].value==root;
s=s+tree[start].value;
else{
s=s+"-|-";
s=s+tree[start].value;
}
if(tree[start].right>0){
s1=s1+"1";
dfs(tree[start].right,s,n+1,s1);
s1=s1.substring(0,s1.length()-1);
}
int len=s.length();
int cot=0;
for(int i=0;i<len;i++){
if(s.charAt(i)=='|'){
if(s1.length()<=cot+1||s1.charAt(cot)!=s1.charAt(cot+1))
System.out.print("|");
else
System.out.print(".");
cot++;
}else if(cot<n){
System.out.print(".");
} else{
System.out.print(s.charAt(i));
}
}
if(tree[start].left>0||tree[start].right>0)
System.out.print("-|");
System.out.print();
if(tree[start].left>0){
s1=s1+"0";
dfs(tree[start].left,s,n+1,s1);
s1=s1.substring(0,s1.length()-1);
}
}
public static void main(String[] args){
Main test=new Main();
Scanner in=new Scanner(System.in);
String A=in.nextLin();
String[] arrayA=A.split(" ");
root= Integer.valueOf(arrayA[0]);
for(int i=0;i<tree.length;i++)
tree[i]=new point();
for(int i=0;i<arrayA.length;i+){
int a=Integer.valueOf(arrayA[i]);
tree[a].value=a;
}
for(int i=1;i<arrayA.length;i++){
int a=Integer.valueOf(arrayA[i]);
int temp=root;
whie(true){
if(a>temp){
if(tree[temp].right==0){
tree[temp].right=a;
break;
} else
temp=tree[temp].right;
}
else {
if(tree[temp].;left==0){
tree[temp].left=a;
break;
}else
temp=tree[temp].left;
}
}
}
String a="";
String s1="";
test.dfs(root,s,0,s1);
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值