How to print out a binary search tree in 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;
}
}