Java Reference
In-Depth Information
You can use recursion to display a binary tree.
Key
Point
Pedagogical Note
One challenge facing the data-structure course is to motivate students. Displaying a binary
tree graphically will not only help you understand the working of a binary tree but perhaps
also stimulate your interest in programming. This section introduces the techniques to
visualize binary trees. You can also apply visualization techniques to other projects.
How do you display a binary tree? It is a recursive structure, so you can display a binary tree
using recursion. You can simply display the root, then display the two subtrees recursively.
The techniques for displaying the Sierpinski triangle (Listing 18.9, SierpinskiTriangle.java)
can be applied to displaying a binary tree. For simplicity, we assume the keys are positive
integers less than
100
. Listings 25.9 and 25.10 give the program, and FigureĀ 25.17 shows
some sample runs of the program.
F
IGURE
25.17
A binary tree is displayed graphically.
L
ISTING
25.9
BSTAnimation.java
1
import
javafx.application.Application;
2
import
javafx.geometry.Pos;
3
import
javafx.stage.Stage;
4
import
javafx.scene.Scene;
5
import
javafx.scene.control.Button;
6
import
javafx.scene.control.Label;
7
import
javafx.scene.control.TextField;
8
import
javafx.scene.layout.BorderPane;
9
import
javafx.scene.layout.HBox;
10
11
public class
BSTAnimation
extends
Application {
12 @Override
// Override the start method in the Application class
13
public void
start(Stage primaryStage) {
14
BST<Integer> tree =
new
BST<>();
// Create a tree
create a tree
15
16 BorderPane pane =
new
BorderPane();
17 BTView view =
new
BTView(tree);
// Create a BTView
18 pane.setCenter(view);
19
20 TextField tfKey =
new
TextField();
21 tfKey.setPrefColumnCount(
3
);
22 tfKey.setAlignment(Pos.BASELINE_RIGHT);
23 Button btInsert =
new
Button(
"Insert"
);
24 Button btDelete =
new
Button(
"Delete"
);
25 HBox hBox =
new
HBox(
5
);
26 hBox.getChildren().addAll(
new
Label(
"Enter a key: "
),
view for tree
place tree view
Search WWH ::
Custom Search