Answer the question
In order to leave comments, you need to log in
How to display a binary tree correctly?
Hello! I study Java, I approached binary trees, read articles on Habré, etc. Everything seems to be clear, but the problem is how to display a binary tree, i. I have an empty tree and how to fill it if entered from the console and how to display it in width? I used code examples, here is an example of input, but how to correctly display in width, so that a beautiful tree would be obtained with output to the console? Using this input and when I tried to output it turned out like something was not right.
public void add(T1 k, T2 v) {
Node<T1, T2> x = root, y = null;
while (x != null) {
int cmp = k.compareTo(x.key);
if (cmp == 0) {
x.value = v;
return;
} else {
y = x;
if (cmp < 0) {
x = x.left;
} else {
x = x.right;
}
}
}
Node<T1, T2> newNode = new Node<T1, T2>(k, v);
if (y == null) {
root = newNode;
} else {
if (k.compareTo(y.key) < 0) {
y.left = newNode;
} else {
y.right = newNode;
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question