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 ...
Related
This is the question I'm working on: Print reverse of a Linked List without actually reversing.
Here is a link to the answer provided by GeeksforGeeks:
I've been looking at what happens step by step with the IntelliJ debug tool but still don't understand how it works.I see that we iterate through the list until the very end and somehow the function starts going backward after we pass the last node? How?Could someone explain this to me please?
void printReverse(Node head)
{
if (head == null) return;
// print list of head node
printReverse(head.next);
// After everything else is printed
System.out.print(head.data+" ");
}
In order to understand this, you need to understand the concept of LIFO (Last In, First Out).
This is the basic concept for a data structured called the stack, which is of great relevance in our case, because the memory section where function calls are being stored is called the stack, because it operates as a stack.
Let's see your method:
void printReverse(Node head)
{
if (head == null) return;
// print list of head node
printReverse(head.next);
// After everything else is printed
System.out.print(head.data+" ");
}
Initially this is called by passing the very first node of your linked list. By the way, let's imagine that your linked list has n elements, of the form of
l(1) -> l(2) -> ... -> l(n) -> null
The i'th call to printReverse checks whether head is null, which, if true, then we have reached the end of the list.
Now, here's what happens:
We reach l(1), which calls printReverse for l(2) and waits for it to complete before printing the value of l(1). The call for printReverse, on l(2), on its turn calls printReverse on l(3) and waits for it to complete, before completing and so on. Once the stack is fully built and we reach the null, then the n+1'th function call returns without a print. Then, the n'th call finishes the printReverse line and prints and so on.
For illustration, let's consider the following list:
1 -> 2 -> 3 -> null
This is what happens:
calling printReverse for the first item
is the node (the first one) null? No
calling printReverse for the second item
is the node (the second one) null? No
calling printReverse for the third item
is the node (the third one) null? No
calling printReverse for the fourth (nonexistent) item
is the node (the null after the last element) null? Yes, do nothing
printing 3
printing 2
printing 1
As you can see, each function call is a level deeper than the former function call and the former function call waits for the functions it called to evaluate. Since it prints after its function calls, this means that when the method reaches the print of a level, all inner levels were already evaluated and printed, reaching the reversed order.
The logic of the recursion is called post-order, in which you define your logic after the recursion call
Assume you have the following LinkedList 1->2->3->null
And you call
printReverse(head)
First will check if the head is null, if yes return (stop don't continue execution)
Second call printReverse by pointing to the next node
Third repeat steps 1 & 2 until hitting the null node
Four print the data
The result will print from the last node to the first node
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...
Because of that to learn very-well logic of behind recursive idea, I'm practising while studying data structures by using debugger. The problem may seem easy but it just makes a sensation. The method finds maximum element in a binary search tree. - As a rule, binary search tree(click here for full implementation) is a tree in which left child has less elements than root element and right child has higher elements than root element. - Until finding it, the method goes into new activation frame and push it onto atop of the stack. Having been found, they are popped off in-reversed order(LIFO). My question is that why does the method return second statement(return findMax(node.right))? If the debugger shows activation frames being popped off, why does it just show the one time? I hope images aid to comprehend my question more as well.
/* bST.add(1),bST.add(3),bST.add(7),bST.add(6),bST.add(4),
bST.add(13),bST.add(14),bST.add(10),bST.add(8); */
/**
* Find max element in the BST
* #param node local node being given
* #return max element
*/
public E findMax(Node<E> node) {
if (node.right == null)
return node.data;
return findMax(node.right);
}
The code works down the right side of the tree until it hits the largest element: the one with no right child. Then it returns the data value of that node -- to the instance that called it. That was the instance called from node 13.
The particular statement return node.data is the base case for this recursion. The second one, return findMax(node.right), is the recursion case. By the time you reach the value 14, you have four of these returns stacked up, waiting for results.
The one from node 13 will then pass the value 14 back to the call from node 7, continuing down the stack until the call from node 1 returns the value 14 to whatever called findMax in the first place.
I don't know why your debugger shows evidence of only the first activation "pop". I don't know what settings you're using. If you're single-stepping, or have a breakpoint set at the return (as well as the findMax call), you should see both ends of that: going down another level, and then coming back up in LIFO order.
Does that clear up anything for you?
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.
i was wondering if anyone could help me with this question. i believe i understand the code and logic for the most part. i can trace code and it makes sense, but one thing i don't get is....how does the LinkedListNode previous actually change the LinkedListNode n that is passed in?
it seems to me that the function loops through n, and if the element is not yet found puts it into a hashtable. but when it is found again, it uses this newly created LinkedListNode previous to skip over the duplicate and link to the following element, which is n.next.
How does that actually disconnect LinkedListNode n? It seems like previous would be the LinkedListNode that has no duplicates, but since nothing gets returned in this function, n must be the one that changes. I guess I'm not seeing how n actually gets changed.
Clear and thorough help would be much appreciated. Thank you = )
public static void deleteDups(LinkedListNode n){
Hashtable table = new Hashtable();
LinkedListNode previous = null;
while(n != null){
if(table.containsKey(n.data))
previous.next = n.next
else{
table.put(n.data, true);
previous = n;
}
n = n.next;
}
}
doesn't the line...
LinkedListNode previous = null;
create a new LinkedListNode?
so this is my logic of how i'm doing it...
lets say the argument, n, gets passed in as
5 -> 6 -> 5 -> 7
when the code first runs, previous is null. it goes into the else statement, and previous is now 5? and then the line n = n.next makes n 6? now the hashtable has 5, and it loops again and goes into the else. prev is now 6 and the hastable has 6. then n becomes 5. it loops again but this time it goes into the if, and prev is now 7. and n will become 7. i see that prev skipped over 5, but ...how is prev unlinking n? it seems like prev is the LinkedListNode that contains no duplicates
how does the LinkedListNode previous actually change the
LinkedListNode n that is passed in?
Look at the line
n = n.next;
This line causes the passed node n to change - effectively moving it one node forward with each iteration.
it uses this newly created LinkedListNode previous to skip over the duplicate and link to the following element
No, no node is newly created here. The node previous always points to a node in the existing LinkedList of which the passed node n is one of the nodes. ( may be the starting node ). What makes you think it is newly created ?
It looks like you are confused in your understanding of how nodes and references ( and so a LinkedList as a whole ) works in Java. Because all modifications occur on the Node's data , and not the reference itself , ( ugh.. thats not entirely correct ), the original LinkedList passed to the method does get modified indeed after the method returns. You will need to analyse the LinkedList structure and workings in details to understand how this works. I suggest first get clarity about what pass by value and pass by references are in Java.
edit :
Your analysis of the run is correct , however your confusion still remains because you are not conceptually clear on certain things.
Towards the end of your analysis , you ask "..how is prev unlinking n? it seems like prev is the LinkedListNode that contains no duplicates "
This is a mess - first , you need to differentiate between a LinkedListNode and a LinkedList itself. prev and n are two instances of LinkedListNode, not LinkedList itself. In your example , the LinkedList is unnamed ( we dont have a name to refer to it ). This is the original list - there is no other list.
Second , in your illustration , the numbers you show are only one part of the node , called the node data. The other part, that you have missed out, is the next LinkedListNode reference that is implicit in every node. The link that you draw -> is actually the next reference in each node.When you say that prev skips 5 , what actually happens is that the next of node with data 6 is made to point to node with data 7.
At start :
5|next -> 6|next -> 5|next -> 7|next->NULL
After 5 is skipped :
5|next -> 6|next -> 7|next->NULL
As you see , the linkedlist is changed ! It does not matter if it was changed using prev or n, the change remains in the list.
if(table.containsKey(n.data))
previous.next = n.next
Is the section which does the deletion. It assigns the reference of the prior node's next field to the node after the current node, in effect unlinking the current node.