Java 打印格式正确的二进制搜索树
我有一个二叉树程序,它将较小/相等的数字排序到父级的左侧,将较大的数字排序到父级的右侧,我想打印出一个图表,但我不知道如何打印它以使其格式良好。此外,print方法应该是TreeDriver类的一部分,还是TreeNode类的一部分,以递归方式访问每个节点 以下是课程: 树形驾驶员:Java 打印格式正确的二进制搜索树,java,binary-tree,binary-search-tree,Java,Binary Tree,Binary Search Tree,我有一个二叉树程序,它将较小/相等的数字排序到父级的左侧,将较大的数字排序到父级的右侧,我想打印出一个图表,但我不知道如何打印它以使其格式良好。此外,print方法应该是TreeDriver类的一部分,还是TreeNode类的一部分,以递归方式访问每个节点 以下是课程: 树形驾驶员: import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; /** * This class ser
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* This class serves as the driver for a generic TreeNode, giving it the type of Integer.
*/
public class TreeDriver
{
//region Instance Variables
TreeNode<Integer> root;
//endregion
//region Constructors
public TreeDriver() throws FileNotFoundException
{
fill();
System.out.println("Count: " + root.getCount());
}
//endregion
//region Public Methods
public void fill() throws FileNotFoundException
{
Scanner reader = new Scanner(new File("TreeValueSource"));
String temp;
Integer entry;
makeRoot();
while (reader.hasNext())
{
temp = reader.nextLine();
if (temp.contains("//"))
{
if (reader.hasNext())
temp = reader.nextLine();
else break;
}
else if (checkInt(temp))
{
entry = new Integer(temp);
root.add(entry);
}
else System.out.println("ERROR IN FILL");
}
}
private void makeRoot()
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a root value(default 50): ");
String input = scan.next();
if (checkInt(input))
root = new TreeNode<>(new Integer(input));
else
root = new TreeNode<>(50);
}
public void printCount()
{
System.out.println(root.getCount());
}
//endregion
//region Private Methods
private boolean checkInt(String candidate)
{
boolean parsable = true;
try
{
Integer.parseInt(candidate);
} catch (NumberFormatException e)
{
parsable = false;
}
return parsable;
}
//endregion
}
导入java.io.File;
导入java.io.FileNotFoundException;
导入java.util.Scanner;
/**
*此类充当通用TreeNode的驱动程序,为其提供整数类型。
*/
公共级树型驾驶员
{
//区域实例变量
树根;
//端区
//区域构造函数
public TreeDriver()引发FileNotFoundException
{
填充();
System.out.println(“Count:+root.getCount());
}
//端区
//区域公共方法
public void fill()引发FileNotFoundException
{
扫描仪阅读器=新扫描仪(新文件(“TreeValueSource”);
字符串温度;
整数项;
makeRoot();
while(reader.hasNext())
{
temp=reader.nextLine();
如果(温度包含(“/”)
{
if(reader.hasNext())
temp=reader.nextLine();
否则就断了;
}
否则如果(检查输入(温度))
{
条目=新整数(临时);
root.add(条目);
}
else System.out.println(“填写错误”);
}
}
私有void makeRoot()
{
扫描仪扫描=新扫描仪(System.in);
System.out.println(“输入根值(默认值50):”;
字符串输入=scan.next();
if(checkInt(输入))
根=新树节点(新整数(输入));
其他的
根=新的树节点(50);
}
公共作废打印计数()
{
System.out.println(root.getCount());
}
//端区
//区域私有方法
私有布尔checkInt(字符串候选)
{
布尔可分解=真;
尝试
{
整数.parseInt(候选);
}捕获(数字格式)
{
parsable=false;
}
返回可解析;
}
//端区
}
TreeNode:
public class TreeNode<T extends Comparable<T>>
{
//region Instance Variables
//Links
private TreeNode<T> leftChild; //Left Link
private TreeNode<T> rightChild; //Right Link
//Properties
private T data; //Info Stored by the TreeNode
private int childCount; //Number of Children
private int depth; //Level of the Node in the Tree
//endregion
//region Constructors
public TreeNode(T data, int parentDepth)
{
leftChild = null;
rightChild = null;
childCount = 0;
depth = parentDepth + 1;
this.data = data;
}
public TreeNode(T data)
{
leftChild = null;
rightChild = null;
childCount = 0;
depth = 0;
this.data = data;
System.out.println("A Root was Created");
}
//endregion
//region Public Methods
/**
* ADD
* Adds a new TreeNode to the tree. Left if equal or smaller, Right if larger
*
* @param data The data held by the TreeNode
* @see TreeNode
*/
public void add(T data)
{
if (this.data.compareTo(data) <= 0)
{
addLeft(data);
} else if (this.data.compareTo(data) > 0)
{
addRight(data);
} else
{
System.out.println("ERROR IN TREENODE.ADD");
}
}
public int getCount()
{
return count();
}
/**
* IS LEAF
* Determines if the current node has no children
*
* @return True if no children, False otherwise
*/
public boolean isLeaf()
{
return childCount == 0;
}
//endregion
//region Private Methods
//Adds the data to the left of this.TreeNode
private void addLeft(T data)
{
if (null == leftChild)
{
leftChild = new TreeNode(data, depth);
childCount += 1;
} else
leftChild.add(data);
}
//Adds the data to the right of this.TreeNode
private void addRight(T data)
{
if (null == rightChild)
{
rightChild = new TreeNode(data, depth);
childCount += 1;
} else
rightChild.add(data);
}
/**
* COUNT
* Recursively counts the number of TreeNodes
*
* @return the number of TreeNodes, 0 if an error
*/
private int count()
{
if (isLeaf())
{
return 1;
} else if (childCount == 2)
{
return 1 + leftChild.count() + rightChild.count();
} else if (null == leftChild)
{
return 1 + rightChild.count();
} else if (null == rightChild)
{
return 1 + leftChild.count();
} else
{
System.out.println("ERROR IN COUNT AT DEPTH " + depth);
return 0;
}
}
//endregion
}
公共类树节点
{
//区域实例变量
//链接
私有树节点leftChild;//左链接
私有树节点rightChild;//右链接
//性质
private T data;//树节点存储的信息
private int childCount;//子级数
private int depth;//树中节点的级别
//端区
//区域构造函数
公共树节点(T数据,int parentDepth)
{
leftChild=null;
rightChild=null;
childCount=0;
深度=父深度+1;
这个数据=数据;
}
公共树节点(T数据)
{
leftChild=null;
rightChild=null;
childCount=0;
深度=0;
这个数据=数据;
System.out.println(“创建了根”);
}
//端区
//区域公共方法
/**
*加
*将新树节点添加到树中。如果相等或更小,则向左,如果更大,则向右
*
*@param data树节点保存的数据
*@see TreeNode
*/
公共无效添加(T数据)
{
如果(此.data.compareTo(数据)0)
{
addRight(数据);
}否则
{
System.out.println(“TREENODE.ADD中的错误”);
}
}
public int getCount()
{
返回计数();
}
/**
*是叶子
*确定当前节点是否没有子节点
*
*@如果没有子项,则返回True,否则返回False
*/
公共布尔isLeaf()
{
返回childCount==0;
}
//端区
//区域私有方法
//将数据添加到此.TreeNode的左侧
私有void addLeft(T数据)
{
if(null==leftChild)
{
leftChild=新树节点(数据,深度);
childCount+=1;
}否则
添加(数据);
}
//将数据添加到此.TreeNode的右侧
私有void addRight(T数据)
{
if(null==rightChild)
{
rightChild=新树节点(数据、深度);
childCount+=1;
}否则
rightChild.add(数据);
}
/**
*计数
*递归计算树节点的数量
*
*@返回树节点数,如果出现错误,则返回0
*/
私有整数计数()
{
if(isLeaf())
{
返回1;
}else if(childCount==2)
{
返回1+leftChild.count()+rightChild.count();
}else if(null==leftChild)
{
返回1+rightChild.count();
}else if(null==rightChild)
{
返回1+leftChild.count();
}否则
{
System.out.println(“深度处计数错误”+深度);
返回0;
}
}
//端区
}
您可以将此答案用作模型
[
修改BtreePrinter类。不,您不应该将print方法放在TreeDriver类中
class Node<T extends Comparable<?>> {
Node<T> left, right;
T data;
public Node(T data) {
this.data = data;
}
}
class BTreePrinter {
public static <T extends Comparable<?>> void printNode(Node<T> root) {
int maxLevel = BTreePrinter.maxLevel(root);
printNodeInternal(Collections.singletonList(root), 1, maxLevel);
}
private static <T extends Comparable<?>> void printNodeInternal(List<Node<T>> nodes, int level, int maxLevel) {
if (nodes.isEmpty() || BTreePrinter.isAllElementsNull(nodes))
return;
int floor = maxLevel - level;
int endgeLines = (int) Math.pow(2, (Math.max(floor - 1, 0)));
int firstSpaces = (int) Math.pow(2, (floor)) - 1;
int betweenSpaces = (int) Math.pow(2, (floor + 1)) - 1;
BTreePrinter.printWhitespaces(firstSpaces);
List<Node<T>> newNodes = new ArrayList<Node<T>>();
for (Node<T> node : nodes) {
if (node != null) {
System.out.print(node.data);
newNodes.add(node.left);
newNodes.add(node.right);
} else {
newNodes.add(null);
newNodes.add(null);
System.out.print(" ");
}
BTreePrinter.printWhitespaces(betweenSpaces);
}
System.out.println("");
for (int i = 1; i <= endgeLines; i++) {
for (int j = 0; j < nodes.size(); j++) {
BTreePrinter.printWhitespaces(firstSpaces - i);
if (nodes.get(j) == null) {
BTreePrinter.printWhitespaces(endgeLines + endgeLines + i + 1);
continue;
}
if (nodes.get(j).left != null)
System.out.print("/");
else
BTreePrinter.printWhitespaces(1);
BTreePrinter.printWhitespaces(i + i - 1);
if (nodes.get(j).right != null)
System.out.print("\\");
else
BTreePrinter.printWhitespaces(1);
BTreePrinter.printWhitespaces(endgeLines + endgeLines - i);
}
System.out.println("");
}
printNodeInternal(newNodes, level + 1, maxLevel);
}
private static void printWhitespaces(int count) {
for (int i = 0; i < count; i++)
System.out.print(" ");
}
private static <T extends Comparable<?>> int maxLevel(Node<T> node) {
if (node == null)
return 0;
return Math.max(BTreePrinter.maxLevel(node.left), BTreePrinter.maxLevel(node.right)) + 1;
}
private static <T> boolean isAllElementsNull(List<T> list) {
for (Object object : list) {
if (object != null)
return false;
}
return true;
}
}
类节点>无效打印节点(节点根){
int maxLevel=BTreePrinter.maxLevel(根);
printNodeInternal(Collections.singletonList(根目录),1,maxLevel);
}
私有静态链接到链接列表的连接在哪里?你的标题有点误导和混乱。我调整了标题,我可以看出它是如何误导的可能的重复