This is wrt to Binary Search Tree.I am traversing the tree in 2 ways.1)InOrder Traversal
An inorder traversal of tree t is a recursive algorithm that follows the the left subtree; once there are no more left subtrees to process, we process the right subtree. The elements are processed in left-root-right order.
2)PostOrder Traversal
A postorder traversal of tree t is a recursive algorithm that follows the the left and right subtrees before processing the root element. The elements are processed left-right-root order.
I am confused over how the recursion methods and print statements are working. Could you please enlighten me?
static void inOrder(Leaf root){
if(root != null){
inOrder(root.left);
System.out.print(root.value+" ");
inOrder(root.right);
}
}
static void postOrder(Leaf root){
if(root != null){
postOrder(root.left);
postOrder(root.right);
System.out.print(root.value+" ");
}
}
The way this works is each function will print out a single, long line containing each of the values if the tree. As each of the algorithms goes through the tree, it appends the current value of the node to the output along with a space. For example, if we consider the following tree:
2
/ \
1 3
The first algorithm will start at the 2, then call itself on the left child, 1. The function will then call itself on the left child, which is null, so it will return immediately. The function will then print "1 " to the console. The function will call itself on the right child, which is null, so it will return immediately. The function will then return to the 2, and "2 " will be printed to the console. The function will then call itself on the right child, which is the 3. The function will call itself on the left child , which returns, then print "3 " to the console, then call itself on the right child, which returns. The function will then return to the 2, and that will return to whatever called it. The console at the end will say
1 2 3
A similar thing would happen for the second algorithm, except the function would go to and print the left and right children, 1 and 3, respectively, before printing the root node, 2, resulting in the following output:
1 3 2
If you are having trouble understanding it, it would benefit you to draw yourself a tree and follow the code step by step to see what the computer is doing.
As every recursion method, it needs a base case, a condition to stop the recursion. In this case, it's when "root" is null.
Observe that the variable root, will only be the actual root of the Tree at the first call in the method. Consecutive calls are passing the element on it's left or right.
On the method inOrder, it prints the elements that are further down on the left branch of the Tree. So it "goes down a level" on the tree before calling the print. This means that if the element has a leaf on a left branch, it will print said leaf before going to the right branch.
in the postOrder Method, it will go the furthest down on the tree it can go and then print the elements, doing that for both branches ( left and right ). This meaning that the leafs of thre tree will be printed first while the actual root will be the last Element.
If you're having trouble visualizing, i suggest you draw the tree in a paper and run the code with a small sample tree using the Debug on Eclipse, so you can follow the execution line by line and see how the algorithm is traversing the Tree.
Related
This is simple code for in-order traversal of a binary tree. I just have a small doubt, if I use while instead of if in this, I get a TLE error. I want to know at what condition it will get stuck?
(I know we use if condition and with recursion should not use while here, but just to understand I want to know)
Can you please explain with a small example taking this small tree as where will get struck in this loop?
1
/ \
2 3
void inorder(Node root) {
**while** (root != null) {
inorder(root.left);
count++;
inorder(root.right);
}
}
The root of the tree is never null. So even if you iterate and traverse the entire tree and it returns back to the initial call of the inorder method, the root will never be null and the while loop will execute again and thus traverse the tree infinitely.
As an example, it starts with 1, then goes to 2, then goes to 3. The first iteration at the root is done. But since the root is never null, it will iterate again by going to 2 then 3 ... infinitely iterating the tree.
I mostly get the recursively programmed in order tree Traversal, but theres just a small gap in my understanding that I want to clarify. when the first recursive method call moves the node pointer all the way to the left, why does the fact that there is a null node cause the method to stop at the last node, move past the recursive call and print the last node. Part of me can just accept that that's just what happens, but what I really don't get is why once you print the last left node, why does it move back up to the right, its as if it treats the recently printed node like it treats the null node. In my mind it would keep moving left, as if repeatedly hitting a wall. I'm not sure how well I'm explaining what I don't get, I'll happily try to rephrase and use pictures if it's not clear. I assume the recursive in order tree Traversal is very standard, though I know of two implementations that do the same thing, but I'll add the method code I'm using in Java to be sure.
public void print(Node<E> e){
if (e != null) {
print(e.left);
System.out.println(e.element);
print(e.right)
}
}
why does the fact that there is a null node cause the method to stop at the last node, move past the recursive call and print the last node
As long as you haven't reached the left most node, you will keep calling print(e.left). Once you reached the left most node, e.left of that node would be null, and print(null) will end the recursion. Once it returns, System.out.println(e.element); will print the left most node.
why once you print the last left node, why does it move back up to the right
Then print(e.right) will be executed. If the left most node has a right child, print(e.right) will recursively print the sub-tree of that right child. Otherwise, it will execute print(null), ending the recursion on that path.
Once print() of the left most node returns, you go back to print() of the parent of that node, so you call System.out.println(e.element); for that parent node, and so on...
I came across a traversing binary search tree function but I can't wrap my head around it. Here's the code:
public void inOrderTraverseTree(Node focusNode){
if(focusNode != null){
inOrderTraverseTree(focusNode.leftChild);
System.out.println(focusNode);
inOrderTraverseTree(focusNode.rightChild);
}
}
Assuming a "two-levels" balanced binary search tree, this is how I understand this recursive method:
Starting with root != null --> inOrderTraverseTree(root.leftChild) method runs
root.leftChild != null --> inOrderTraverseTree(root.leftChild.leftChild) method is runs
However, since root.leftChild has no leftChild --> focusNode.leftChild == null, the if loop will not run
in that case, isn't that supposed to mean that nothing ever gets printed?
But it supposedly works (https://www.youtube.com/watch?v=M6lYob8STMI). Can anyone point out where I've gone wrong?
The logic applied here:
Check the focused node. If null then return to parent's inOrderTraverseTree. But since nothing happens after the check for null, an additional return statement is same as no statement at all.
If not null, repeat from (1) for the left child node.
Print the value of the focused node.
Repeat from (1) for the right child node.
Return from current node's inOrderTraverseTree to parent node's inOrderTraverseTree.
Of course, if the focused node is the root node, inOrderTraverseTree simply returns to main, or the method that first invoked it
As an example, consider the tree below:
A
/ \
B C
/ \ / \
D E F G
Trace:
A->inOrderTraverseTree(left)
B->inOrderTraverseTree(left)
D->inOrderTraverseTree(left) //null, return to D
print(D)
D->inOrderTraverseTree(right) //null, return to D
return to B
print(B)
B->inOrderTraverseTree(right)
E->inOrderTraverseTree(left) //null, return to E
print(E)
E->inOrderTraverseTree(right) //null, return to E
return to B
return to A
print(A)
A->inOrderTraverseTree(right)
//Continue for the right subtree.
You need to understand the basic recursion and binary search tree structure here. Lets take below tree to understand this algorithm:
Steps:
1. Focus Node is 9 , since it is not null, thus , inOrderTraverseTree
is invoked with focus node as 7(with left node to 9)
2. Focus Node is 7 , since it is not null, thus , inOrderTraverseTree is invoked with focus node as null(with left
node to 7)
3. Focus Node is null , thus , if condition is not satisfied and execution of function call at step 2 continues.
4. Control goes to method call with node as 7 (since left node was blank) and 7 is printed at System.out.println statement.
5. Now inOrderTraverseTree for focus node null is invoked (with right node to 7)
6. Focus Node is null , thus , if condition is not satisfied and execution of function call at step 2 continues.
7. inOrderTraverseTree for focus node 2 exits and control goes to method call with node as 9.
8. Control goes to method call with node as 9 and 9 is printed at System.out.println statement.
9. inOrderTraverseTree for focus node 11 is invoked (with right node to 9)
10.inOrderTraverseTree for focus node null is invoked (with left node to 11), thus, if condition is not satisfied and control is sent
back to step 9
11. Control goes to method call with node as 11 and 11 is printed at System.out.println statement.
12.inOrderTraverseTree for focus node null is invoked (with right node to 11), thus, if condition is not satisfied and control is sent
back to step 9.
And the execution ends
However, since root.leftChild has no leftChild --> focusNode.leftChild
== null, the if loop will not run
No, it will. since it is recursive it will continue doing for previous calls, check for righchild node in this case.
watch the call order of the function:
it continues ...
Dear Friends I am an intermediate java user. I am stuck in a following problem. I want to construct a unordered binary tree [or general tree having at most two nodes] from a multi line (let say 40 lines) text file. The text file is then divided into two halfs; let say 20:20 lines. Then for each half a specific (let say hash) value is calculated and stored in the root node. So each node contains four elements. Two pointers to the two children (left and right) and two hashes of the two halfs of the original file. Next for each half (20 lines) the process is repeated until at each leaf we have a single line of text. Let the node have
public class BinaryTree {
private BinaryTreeNode leftNode, rightNode;
private String leftHash,rightHash;
}
I need help for writing the tree construction and searching functions. Well searching is performed by entering a line. Then hash code is created for this query line and compared against the two hashes saved at each node. If the hash of query line is close to leftHas then leftNode is accessed and if the hash of query line is close to rightHash then rightNode is accessed. The process continues until an exact hash is found.
I just need the tree construction and search teachnique. The hash comparison etc are not a problem
You'll need to start by reading the file into a string.
The first character in the string could be used as the root. Root + 1 would be the left, root + 2 would be the right
Consider left node of the root (Root + 1), you could also consider this as Root + N. Meaning that the right node would be Root + N + 1.
You can now recursively solve this problem by establishing which Node you are currently on, and setting the left and right now respectively.
So lets think about it,
You have the root node, left node, and right node established. At this point you have used 3 letters/numbers (it really doesnt matter if it is unordered). The next step would be to move down one level and start filling the left, you have the root, you need left and right nodes. Then move to the right node, do the left and right node of this and so on and so forth.
Think about that for a little bit and see where you get.
Cheers,
Mike
EDIT:
To search,
Searching a binary tree is also a recursive theme. (I thought you previously said the tree was unordered, which may change how the tree is laid out if it is suppose to be order).
If it is unordered, you can simply recurse the tree in a manner such that
A.) Check root node
B.) Check left node
C.) Continue checking left nodes until either there is a match, or no more left nodes to check
D.) Recurse back 1, check right node
E.) Check left nodes,
F.) Recuse back, check right node
This theme will continue until eventually you have checked ALL left nodes first, and then the right nodes. The KEY to this, is at any point you have a root node, go left first, then right. (I forget what traversal type this is, but there are others if you wish to implement them over this, i personally think this is the easiest to remember).
You will then repeat for right child of Root node.
If at any time you get a match, exit.
Remember this is recursive, so make sure you think your way through this step by step. It is recursive by definition, in that you will always do steps x,y,z for each part of the tree.
To beat a dead horse, lets look at just 3 nodes to start.
(simplified)
First the root,
if(root == (what your looking for))
{
return root
}
else if(root.leftNode == (what your looking for))
{
return root.leftNode
}
else if(root.rightNode == (what your looking for))
{
return root.rightNode
}
else
{
System.out.println("Value not found")
}
If you have 5 nodes, that would be root would have a left and right, and the root.leftNode would have a left and right... You would repeat the steps above on root.leftNode also, then search root.rightNode
If you have 7 nodes, you would search ALL of root.leftNode and then recurse back to search root.leftNode.
I hope this helps,
pictures work much better in my opinion when talking about traversing trees.
Perhaps look here for a better visual
http://www.newthinktank.com/2013/03/binary-tree-in-java/
So Currently I have a program that creates a huffman tree. the tree is made up of "Hnodes" with these fields: right (points to right child) left (points to left child) code (string of integers, ideally the 0's and 1's that will be the huffman code of this node) character (the character contained in the node).
I have created the huffman tree by adding nodes from a linked list - i know the tree was created correctly. As i created the tree, i told the node when i gave it a parent node, that if it was the parent's "right", its code string was 1, if left 0. However obviously after the entire tree is created, each node is only going to have either a 0 or 1, but not yet a string like 00100101. My question is, now that I have this tree, can can I traverse it? I understand the thought would be to give each child its parent's code + the child's own code, but I do not understand how to loop through the tree to accomplish this.
Thank you in advance.
Maybe this?
ExpandBinaryPaths(node, prefix)
1. if node is null then return
2. else then
3. node.binary = prefix concat node.binary
4. ExpandBinaryPaths(node.left, node.binary)
5. ExpandBinaryPaths(node.right, node.binary)
6. return
The idea is you would call this on the root with no prefix... ExpandBinaryPaths(root, "").