[英]Printing Java Binary search tree
How to print out a binary search tree in java? 如何在Java中打印出二进制搜索树? I have written the code to insert to the tree but without being able to print the tree i am insure if the elements are adding.
我已经编写了插入树的代码,但是无法打印树,因此我无法确定元素是否正在添加。 I will post my code below.
我将在下面发布我的代码。
public class TreeNode {
TreeNode left;
TreeNode right;
TreeNode root;
int data;
public TreeNode(int d) {
data = d;
left = right = null;
root = null;
}
public synchronized void insert(int d) {
if (root == null){
root = new TreeNode( d );
}
if (d < data) {
if (left == null) {
left = new TreeNode(d);
} else {
left.insert(d);
}
} else if (d > data) {
if (right == null) {
right = new TreeNode(d);
} else {
right.insert(d);
}
}
}
public TreeNode treeSearch(TreeNode root, int target) {
if (root != null) {
if (target < root.data) {
root = treeSearch(root.left, target);
} else if (target > root.data) {
root = treeSearch(root.right, target);
}
}
return root;
}
}
You may use following method: 您可以使用以下方法:
void printTree(TreeNode node, String prefix)
{
if(node == null) return;
System.out.println(prefix + " + " + node.data);
printTree(node.left , prefix + " ");
printTree(node.right , prefix + " ");
}
Initial call should be printTree( root,"");
初始调用应为
printTree( root,"");
from where you want to print the tree. 从您要打印树的位置开始。 Here
root
is reference of root node. root
是root
的参考。
UPDATED: 更新:
You can see this code working here 您可以看到此代码在这里工作
you can print the tree data like this. 您可以像这样打印树数据。
public void printTree(TreeNode root) {
if (root == null) return;
System.out.println(root.data);
printTree(root.left);
printTree(root.right);
}
private void print(PrintWriter out) {
print(root, out, "");
}
private void print(TreeNode subtree, PrintWriter out, String indent) {
if (subtree != null) {
print(subtree.left, out, indent + "--");
out.printf("%s %s%n", indent, subtree.data);
print(subtree.right, out, indent + "--");
}
}
Infix order: Left - root - right 中缀顺序:左-根-右
public String printInfix(TreeNode root) {//prints all the words in the tree in infix order
if(root==null) {
return "";
}
return printAll(root.left+" "+root.data+" "+printAll(root.right);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.