CSE143 Simple Binary Tree handout #24
Class TreeNode.java
-------------------
// TreeNode is a class for storing a single node of a binary tree of ints.
// It has just data fields and constructors.
public class TreeNode {
public int data; // data stored at this TreeNode
public TreeNode left; // reference to left subtree
public TreeNode right; // reference to right subtree
// post: constructs a leaf node with given data
public TreeNode(int data) {
this(data, null, null);
}
// post: constructs a TreeNode with the given data and links
public TreeNode(int data, TreeNode left, TreeNode right) {
this.data = data;
this.left = left;
this.right = right;
}
}
Class Tree.java
---------------
// Stuart Reges
// 11/14/05
//
// Simple Tree class that constructs a random tree and that includes a method
// to print the data using a preorder traversal.
public class Tree {
private TreeNode root;
// post: constructs a random tree
public Tree() {
root = randomTree();
}
// post: returns a reference to a randomly constructed tree
private TreeNode randomTree() {
int n = (int) (Math.random() * 100);
if (n < 50)
return null;
else
return new TreeNode(n, randomTree(), randomTree());
}
// post: prints the data fields of the tree, one per line
public void printPreorder() {
printPreorder(root);
}
// post: prints the data fields of the tree using a preorder traversal
private void printPreorder(TreeNode node) {
if (node != null) {
System.out.println(node.data);
printPreorder(node.left);
printPreorder(node.right);
}
}
}