I'm trying to write a code for the preorder traversal of a Binary Threaded tree in java. I wrote the following code, and it holds for a few examples, but I'm worried that I'm overlooking some edge scenarios.
MORE INFO
A node has two references left and right pointing to the left and right child of the node respectively. A boolean field called successor determines if the right pointer points to a child or the successor according to inorder traversal (if successor==false: right points to child, else points to inorder traversal successor)
It would be most appreciated if someone could point out the flaws in my logic here...
public void threadedPreorder(){
IntThreadedTreeNode prev, p=root; //pointers to binary tree nodes
while(p!=null){
while(p.left!=null){ //traversal to leftmost node
visit(p); //while visiting it
p=p.left;
}
visit(p);
prev=p;
p=p.right; //shift to right or successor
if(p!=null && prev.successor){ //avoid visiting the same node twice
while(p!=null && prev.successor){
prev=p;
p=p.right;
}
}
}
}
Any help would be appreciated...:)
First things first... You should write unit tests to find functional bugs
However you seem to have a bug here... while loop does not execute at all
if(p!=null && prev.successor){
while(p!=null && !prev.successor){
prev=p;
p=p.right;
}
}
You may want to replace it with do-while
Related
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...
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.
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/
If given the following tree structure or one similar to it:
I would want the string ZYXWVUT returned. I know how to do this with a binary tree but not one that can have more than child nodes. Any help would be much appreciated.
This is called a post-order traversal of a tree: you print the content of all subtrees of a tree before printing the content of the node itself.
This can be done recursively, like this (pseudocode):
function post_order(Tree node)
foreach n in node.children
post_order(n)
print(node.text)
If you are maintaining an ArrayList (say node_list) to track the number of nodes branching of from the current tree node, you can traverse the tree from the root till you find a node that has an empty node_list. This way you will be able to identify the leaf nodes of the tree. A recursive approach would work for this case. I haven't tested the code but I believe this should work for what you have asked:
If you are maintaining something similar to the class below to build your tree:
class Node {
String data;
ArrayList<Node> node_list;}
The following recursive function might be what you are looking for:
public void traverse_tree(Node n){
if(n.node_list.isEmpty()){
System.out.print(n.data);
}
else{
for(Node current_node:n.node_list){
traverse_tree(current_node);
}
System.out.println(n.data);
}
}
Essentially what you are looking at is the Post-order Depth First traversal of the tree.
something like this should do it
public void traverse(){
for(Child child : this.children){
child.traverse();
}
System.out.print(this.value);
}
I have a transverse tree written in JSP which goes through an XML file.
When I get to a certain Text Node, I'd like to be able to search back up the tree to find a certain element associated with that node.
I'm thinking I need to do a For loop and use some kind of 'getLastNode' or 'getParentNode' function. Would this be the correct method? I'm a little unsure of the syntax, so any help would be much appreciated!
I did a bit of search and I can't find anything which demonstrates what I'm trying to do nor can I find a list of the functions I'm after.
You need to keep calling getParentNode until you hit a node matching your criteria. For example:
public Node searchUpFor(String tagToFind, Node aNode) {
Node n = aNode.getParentNode();
while (n != null && !n.getNodeName().equals(tagToFind)) {
n = n.getParentNode();
}
return n;
}