Using the TreeNode class and the picture of the binary tree below, write the cod
ID: 3687661 • Letter: U
Question
Using the TreeNode class and the picture of the binary tree below, write the code that generates this tree.
private class TreeNode
{
private String data; // hold the entered string
private TreeNode left; // reference to left child
private TreeNode right; // reference to righ child
// constructor will be given an element and create
// a node with the passed string and assign null to
// both left and right children.
public TreeNode(String elementReference)
{
data = elementReference;
left = null;
right = null;
}
}
public void hardCodeATree()
{
// this will create a root node and give it "A"
// create the rest of the nodes
Explanation / Answer
public class BinaryTree
{
public static void main(String Args[])
{
TreeNode tree = new TreeNode( 20 );
int[] nums = {15, 200, 25, -5, 0, 100, 20, 12, 126, 1000, -150};
for(int i : nums )
{
tree.addNode( i );
}
tree.traversePreOrder();
tree.traverseInOrder();
tree.traversePostOrder();
}
}
private class TreeNode
{
private int data;
private TreeNode left;
private TreeNode right;
public TreeNode(int num) {
this.data = num;
this.left = null;
this.right = null;
}
public void addNode(int num) {
if (num < this.data) {
if (this.left != null) {
this.left.addNode(num);
} else {
this.left = new TreeNode(num);
}
} else {
if (this.right != null) {
this.right.addNode(num);
} else {
this.right = new TreeNode(num);
}
}
}
// Visit the node first, then left and right sub-trees
public void traversePreOrder() {
System.out.println( this.data );
if( this.left != null ) {
this.left.traversePreOrder();
}
if( this.right != null ) {
this.right.traversePreOrder();
}
}
// Visit left sub-tree, then node and then, right sub-tree
public void traverseInOrder() {
if( this.left != null ) {
this.left.traverseInOrder();
}
System.out.println( this.data );
if( this.right != null ) {
this.right.traverseInOrder();
}
}
// Visit left sub-tree, then right sub-tree and then the node
public void traversePostOrder() {
if( this.left != null ) {
this.left.traversePostOrder();
}
if( this.right != null ) {
this.right.traversePostOrder();
}
System.out.println( this.data );
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.