Can someone help me understand a Java Binary Tree?

Status
Not open for further replies.

RTfartE

Wise, Aged Ars Veteran
181
I understand how the Binary Tree works, but I just don't understand how it "knows" where it is in the tree, and how it can access the next value just by using a Node left or right. It is quite confusing, so is there anyone that can explain it better than I've gotten it explained, also, if you have some syntax of a basic BT, please post that, too. I appreciate all of the help.
Artie Fartie
 

Magus

Ars Tribunus Militum
1,726
OK, each node has two references: one to a left child node, one to a right child node. You have a reference to the current node that's updated when you move.

So,
code:<HR>
Code:
currNode = currNode.left;
means "move the reference to the current node to the current node's left child node, which makes that child node the current node".

Make sense?

-Magus
 

RTfartE

Wise, Aged Ars Veteran
181
that makes sense, I just don't know how to implement it. So far in class we have just discussed the logistics of it, not actually gotten into Syntax. It makes great sense to me in theory, but I couldn't use it in a program if my life depended on it. Could someone build a BT with the numbers added in this order: 5, -2, 11, 7, -34, 1. Add as many other numbers as you please, I just need to see the syntax to grasp this concept. Thank you,
Artie Fartie
 

Malyk

Ars Tribunus Angusticlavius
8,558
Subscriptor
You don't actually need to 'know' where you are in the tree to find things in a tree. It happens automagically.

::Disclaimer...I've only written one binary tree for a class a few years ago, so the below info might not be 100% correct::

Actually, I'm having trouble coming up with a way to explain this.

Ok, when going through the tree, you start at the top node. You can go either one of two ways. left or right. So you have to make a decision about which way you want to go. This is exactly what you have to do throughout the tree. Get to a node, check the value of the node, and decide whether to go left or right. Then you go right and get to another node where you have to make another decision. Left or right. You keep doing this until you either find what you are looking for, or you hit a node where your decision results in a direction where there is no other node, in which case you either don't have what you are looking for, or you need to go back up the tree to look for something else.

The beauty of this is that it only requires a single function. The function that looks at the first node and decides what to do is the same function that looks at the nth node and decides what to do. So you start at the top calling your function, make a decision, and then call the same function again. This allows you to traverse down through the tree, and back up again, and back down, etc. in a single function.

I'm not sure how much sense that made, but essentially, you don't need to know that you are on the nth left node from the xth right node from the left kth node. It doesn't matter. Each node has the same structure, and so you can think about every node you are currently on as the root node.

Mike
 

RTfartE

Wise, Aged Ars Veteran
181
code:<HR>
Code:
 public class binarytree
{
	public void Insert(Node, num)
	{
		if (num = node.num) return;
			if(num < node.num)
			if(node.left == null)
				Node.left = new Node(num);
			else 
				Insert(Node.left, num);
			
			//end of left case, starting right case
			
			if(num > node.num)
				if(node.right == null)
					Node.right = new Node(num);
				else
					Insert(Node.right, num);	
	}	
}
but I still don't know how to make this work right in ACTUAL implementation. the above code will not work as is, but we weren't instructed as to what to do to make it work.
Artie Fartie
 

Malyk

Ars Tribunus Angusticlavius
8,558
Subscriptor
code:<HR>
Code:
          5
         / \
       -2   11
       /    /
     -34   7
          /
         1<P>

That's what the tree looks like IF you were adding the numbers to the tree based on < or > the root number. Now, to search through the tree you would start with a number to find (or add).

code:<HR>
Code:
traverse(Node *node, int num)
{
   if (num = this->value)
      return true;
   else if (num < this->value)
     traverse(this->left, num)
   else
     travers(this->right, num)
}

That code isn't complete, but it's a start. If you start we start looking for the number 7 then the steps that will happen are:

- Check to see if 7 is < or > 5.
- it's > 5 so you move to the right node
- check to see if 7 is < or > 11
- it's < 11 so you move to the left node
- check to see if 7 = 7
- it does, so we leave the function.

oops...gotta run to happy hour! I'll check back here in a little while!

Mike
 

Shadar Mahdi

Smack-Fu Master, in training
58
Normally I don't write code but for some reason I'm feeling funky today and sorta remember when I looked at a binary tree and puzzled over how it works for a long time but at least our Prof gave us pretty much working code.
So lemme throw in some extra stuff that will let you use the code that you posted to help you actually SEE what you do with the scaffolding to do something useful.

Note that when it comes to implementing trees unless you really want to hurt your brain, think and program recursively. If you try thinking in a looping manner it gets much harder to implement a tree. I a good chunk of a week thinking about doing it without recursion and decided after getting pretty close to something that it wasn't worth the effort.

Please excuse my bad syntax as I've not looked at Java for at least 8 months and I'm writing this off the top of my head but I think you'll get the idea of how to USE a Binary Tree with the rest of the code given:

code:<HR>
Code:
<P>// Little cheezy helper class so that the Node objects
// will be created as well
public class Node {
	int x;
	Node ( myInt) {
		x = myInt;
	}
}<P>
public class useBinaryTree {
// The point of this is to actually use the code given
// to insert some values into the binary tree<P>// Create an array of ints [5, -2, 11, 7, -34, 1] that
// we are going to stuff into our binary tree
	int[] temparray = { 5, -2, 11, 7, -34 1 };
// Create an instance of the tree so we can actually dump
// our goodies somewhere
	binarytree myTree = new binarytree();<P>// Loop and keep adding elements into the tree
	for (int i=0; i<temparray.length; i++ ) {
		myTree.Insert(new Node(temparray[i]));
	}
}
 
OK, each node has two references: one to a left child node, one to a right child node.
Actually, a lot of tree implementations also have a pointer to the parent note. It makes non-recursive traversal much easier (well, at least possible without a stack), and most importantly it makes iterators possible (again, without a stack).

As for finding a value... think of it this way. You've got this huuuuuuuuuuuge tree there. You know that on the left branch all values are smaller than x, and on the right branch all values are bigger than x. Let's say you also know that your value is bigger than x. You rip off the right branch, and throw away the left one. But guess what? That branch is so big it also looks like a tree now that you've got it in your hands. So you start all over :)
 

iceburn

Wise, Aged Ars Veteran
195
Subscriptor
Don't mean to be a nitpicker, but the tree would look like this:

code:<HR>
Code:
  <P>      5
    /   \
  -2    11
  / \   /
-34 1  7

It took me a while to wrap my head around the binary tree thing too. If you can understand it in theory, just remember that if you step through one node at a time and compare the node with the number you're searching for, you'll always end up in the right place. If you do it recursively, you don't have to worry about knowing where you are in the tree, just worry about which direction to go next.
 

OneFootsTheSame

Smack-Fu Master, in training
70
In case anyone is interested, doing a simple OO binary tree in Java (just a class with the value, node references left/right, and a basic traverse) is my #1 favorite question to ask in an interview. Especially of a new grad (BS or MS). I learn more from this one question then from a dozen "tell me what you know about OO" questions, and it's amazing how many people simply fall on their face.
 

Malyk

Ars Tribunus Angusticlavius
8,558
Subscriptor
Don't mean to be a nitpicker, but the tree would look like this:

DOH! I was trying to run out to happy hour. That's my excuse. :oops:)

On the interviewing subject...How many people actually ask people to answer these types of questions in an interview? I only went on 1 interview when I graduated, and all we did was chat the whole time.

I wouldn't have had a problem writing an answer to that problem in an interview...at least the framework for it. It's a lot more difficult to write code on paper that you can't test than it is to actually implement on a computer. I think it would take me hours to write a binary tree algorithm that I knew worked on paper, but only 15 minutes in front of a computer.

Mike
 
Employers (and ex-employers) told me that there'd be a programming "test" to be had, but it's always ended up we talk methodology and I get the job.
At any rate, if you're dealing with a tree, never forget to keep a static link to the head node. I've seen it said, but if you're new to the linked list game (even in Java), you'll end up doing and seeing interesting things if you can't find the root of the tree.
Alternatively, you can implement what amounts to a triply-linked list (two children and the parent), but it'll be a waste of memory (and potentially slower to boot) in the long run.
 
Originally posted by gubmo:
You need to keep a reference to the real top of the tree, or the virtual top that you just got from 'hacking off' the rest of it?

It looks like I need to write some code...

gubmo

As long as you know where you are, you will always know where the virtual top that you got from "hacking off" the rest of it is; that will always be one of the children of your current node. What he's speaking of is keeping a pointer to the overall root node of the tree.

floccinau
 

RTfartE

Wise, Aged Ars Veteran
181
I would like to thank everyone for all of the help, but I still don't know the syntax :( I have tried piecing together a basic bintree, but the results have still left me bamboozled because I have never seen the complete components of a tree program. If someone has the complete BinTree program w/ subclasses included, could they please post them to help me understand what the syntax is doing. Thank you so very much :)
Artie Fartie
 

-Triple-

Ars Tribunus Angusticlavius
8,554
The pseudocode to traverse a tree and do something in infix is as follows:

code:<HR>
Code:
function traverse (pointer p)
  if the left pointer of p isn't null
    traverse(left pointer of p)<P>  operation on node here<P>  if the right pointer of p isn't null
    traverse(right pointer of p)
end function

That, and an understanding of recursion, is all you need. Just step through the algorithm recursively and you'll understand.
 
Status
Not open for further replies.