-
Binary tree
Hi guys i'm having trouble understanding the following homework question.
I have done most of the work, but don't get the sample output expected. This is probably because i have miss understood the way our professor wants us to insert Values. I have given my insert method and sample output. Can you guys see if i'm doing something wrong
Home Work question
Write a program called A02Q05 that accepts a series of integers as command line parameters. The
integers should be inserted into a binary tree in the order that they occur in the series. In other
words, the series is a level-by-level traversal.
**Sample outPut**
>java A02Q05 4 5 2 7 3 6 8
preorder: 4 5 7 3 2 6 8
inorder: 7 5 3 4 6 2 8
postorder: 7 3 5 6 8 2 4
**My Output**
Preorder Traversal:
4 2 3 5 6 7 8
Inorder Traversal:
2 3 4 5 6 7 8
Postorder Traversal:
2 3 5 6 7 8 4
My insert Method
Code:
public void insert(Node newNode) {
Node tempNode = null;
Node rootNode = root;
while (rootNode != null) {
tempNode = rootNode;
if (newNode.getKey() < rootNode.getKey()) {
rootNode = rootNode.getLeftChild();
} else {
rootNode = rootNode.getRightChild();
}
}
newNode.setParent(tempNode);
if (tempNode == null) {
root = newNode;
} else if (newNode.getKey() < tempNode.getKey()) {
tempNode.setLeftChild(newNode);
} else {
tempNode.setRightChild(newNode);
}
}
Cheers
-
Re: Binary tree
Homework doesn't belong in 'Advanced Java'. Moving to 'New to Java'
db