I'm trying to implement code that takes a queue, titled 'input,' that has an arithmetic expression.
The expression looks like this:
5 - a * 6 + b
This expression is stored into a queue and I have a method that checks the type of whatever I'm popping in my queue. The method is called getIt() and it returns an integer that tells if it is either an operand or operator. 1 is equal to an operand; 0 is equal to operator. So if I call queue.pop() which should return the value pop the value '5', the getIt() method call on that pop would return 1.
I have an add method that takes in a queue and is supposed to add the values of the queue into a binary tree using the in order system.
BinNode<Term> current = new BinNode<>();
BinNode<Term> parent = new BinNode<>();
current = null;
parent = null;
for (int i = 0; i < input.size(); i++) {
if (input.pop().getType() == 1) {
current = new BinNode<Term>(input.pop());
} else if (input.pop().getType() == 0) {
parent = new BinNode<Term>(input.pop());
parent.setLeft(current);
}
}
In this code, I create two nodes called current/parent. I created a loop that would iterate through the queue, check to see if a popped value would be an operand-- if yes, then I set the current node to that popped value. If it's an operator, I set that to the parent node and set the left node to current. My issue here is how I finish the tree. If the goal of the tree is to make it appear similar to
*
/ \
- +
/ \ / \
5 a 6 b
I dont know how I can get my code to reflect this.
Related
I am building a tree structure in java from scratch. For getting the height of my tree I am using a recursive function.
Each note (IP) contains a list of all connections it has, including there parent. My idea was to loop over all children and call the height function again when it's not the parent.
My problem is, that it only calls one child and does not loop over all possible children. Maybe someone can tell me where is my fault.
If one Note has two children and each of them also has another two. It only views the first one at both iterations.
public int recursiveGetHight(final Node node, Node parent) {
Node viewPoint = getViewPoint(node);
int h = 0;
for (Node child : viewPoint.getChildren()) {
if (child.getChildren().size() <= 1) {
return 0;
} else if(parent == null || child.getValue() != parent.getValue()){
h = recursiveGetHight(child, viewPoint) + 1;
return h;
}
}
return h;
}
Exempel:
root
- note 1
- sub note 1
- sub note 2
- x
- y
- note 2
- sub note 1
- z
- sub note 2
int h = recurisvHeight(root, null)
result should be 3 but the function returns 2.
If I at a print command inside the for loop
System.out.println(child);
it shows:
note1
sub note 1
It's because you use return, when you make a return your function end.
You have to remove the first return = 0 and make an ArrayList of child and replace return h in the by loop by append the child in the list.
public class GetElementWithoutPop {
public static void main(String args[]) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
stack.push(60);
System.out.println("value is: " + GetElementWithoutPop.getStackElement(stack, 3));
System.out.println("stack is " + stack);
// Using Java
int position = 3;
Integer result = stack.get(position);
System.out.println(result);
}
public static <T> T getStackElement(Stack<T> stack, int index) {
if (index == 0) {
return stack.peek();
}
T x = stack.pop();
try {
return getStackElement(stack, index - 1);
} finally {
stack.push(x);
}
}
}
Till the index becomes 0 from 3 it's all good and simple, but after that the code goes back to try block and then again to finally block and the index starts to increase on its own all the way back to 3 and stack.push(x) brings the stack back to its original state.
How is this happening?
Fairly new to recursions & I need to understand this!
This happens because each function call has its own unique context for the same function so the variable x stores the popped variable and calls recursively to pop further value but that value is stored in x of the next function call, while returning the finally block runs and each unique value of x in each function call is again pushed
T x = stack.pop(); // this value remains stored in the function call stack
try {
return getStackElement(stack, index - 1); // same function runs for further case (n-1) th and stores the value in its own x variable in its context
} finally {
stack.push(x); // after the control returns, this copy of function has its unique x variable and that is pushed again
}
You mention that "index starts to increase on its own all the way back to 3 .." that's because each function call has its own set of variables including index
Some Steps
1) Function call instance with index 3 calls function with index 2
2) Function call instance with index 2 calls function with index 1
3) Function call instance with index 1 calls function with index 0
4) Control returns
5) Now the control is back to instance with index value 1
6) Control returns from even that instance and now is back to instance with index 2
This is like winding and then unwinding,, while solving problems with recursion we have to often decide whether we want to do some work at call for n and then call for n-1 OR call for n-1 , let the control return and then do some work
I'm facing the classic "It works, but I don't know why!"-problem. I just applied a principle that I knew from another excercise with integers, but here I have to work with trees. The testing of the method was successfull. I am supposed to count the knots of a tree, and I do this bis traversing through it (in this case: inorder), and every time I traverse successfully (meaning: not facing an empty sub-tree), I count that as a knot. In this case, I'm wondering why this code doesn't count too much knots. For example, when I always go left and face an empty sub-tree, wouldn't I go up until I reach a knot where I can go right? Why does my code avoid this kind of problem?
public static int numberKnots (Tree b) {
int count = 0;
if (b.empty()) {
return 0;
}
else {
traverse.inorder(b.left());
traverse.inorder(b.right());
count = 1;
}
return count + numberKnots(b.left()) + numberKnots(b.right());
}
You do not really travel up and down the tree, you only travel down and visit each node once, and you do this by making your trees More and more simple.
Consider The following tree
a
/ \
b c
/ \
d e
So you start from the root and check if it is empty which it is not, so you return the result of 1 + numberKnots(left) + numberKnots(right). left and right are also trees and they are simpler than a
left right
b c
/ \
d e
So now you check the b tree, which is empty so it just returns 0. Then you check the c tree, which is not empty so you return 1 + countKnots(left (of c)) + countKnots(right (of c)) and so on.
Each step of the calculation would be:
countKnots(a)
= 1 + countKnots(b) + countKnots(c)
= 1 + 0 + countKnots(c)
= 1 + 0 + 1 + countKnots(d) + countKnots(e)
= 1 + 0 + 1 + 0 + countKnots(e)
= 1 + 0 + 1 + 0 + 0
= 2
Your code could be simplified to
public static int numberKnots (Tree b) {
if (b.empty()) {
return 0;
} else {
return 1 + numberKnots(b.left()) + numberKnots(b.right());
}
}
However, it does not seem to handle tree nodes which does not contain both left and right nodes, so the following tree would cause an error
a
\
c
Since you are using recursion,it does not transverse the same node twice.So your code works perfectly fine.consider (A) has two child nodes (B)&(C) further (B) has two childs (B1)&(B2).when transversing through recursion,it usses stack."(consider s to be our stack)". First the control reaches node(A) and since it has left child (A) is pushed into stack and control is trasferred to (B) now control is trasferred to (B)'s left child(B1) and (B) is pushed into stack, since (B1) does not have any childs it is counted and control is trasferred to top of stack i.e (B) and (B) is counted now control is trasffered to (B)'s right child it (B2)and (B2) is counted and control is trasferred to (B).Now (B) does not have any part of code left thus it is popped from stack and control is trasfered to (A) and (A) is counted and control is transfered to its right child (c).Similarly all nodes are counted without duplicating.
Hope it helps
I am trying to understand the concept of recursion. I understand how it works if there is one recursive statement in the code (example factorial)
I dont understand how code like this to calculate the depth of a binary tree would work:
public int getDepth(Node root)
{
if ( root == null) return 0;
int left = getDepth(root.left);
int right = getDepth(root.right);
if (left > right)
return left + 1;
else
return right + 1;
}
I see why this works but not how. Can someone explain to me how the second recursive call (getDepth(root.right)) works? What would this code look like in the memory? When getDepth(root.left) is recursive called does that stack ever go to the if statement at the every bottom?
What happens is that each consecutive call to getDepth is completely separate and thus the bound variables are separate and it follows it's arguments and is oblivious that it's called from a version of itself with different arguments.
When you do getDepth(null) you get 0 since it's the very base case on the first line. However if you send it getDepth(new Node(null, null)) it will call getDepth(root.left) which is the same as getDepth(null) and turns into 0 for both left and right and the result is 0 + 1.
If you would bind the previous node to a variable node and try getDepth(new Node(node, node)) it will do both left and right again where both of them would be the answer of the previous test 1. The result would be 1 + 1, thus 2.
You can continue like this and just assume the result based on the previous calculations. By looking from a complex argument you need to imagine that each consecutive recursion starts fresh with it's arguments and that follows the same pattern. When a result is passed back the caller continues to the next line. In a tree structure like:
1
/ \
2 3
/\ /\
4 5 6 7
I just numbered the nodes and not included null nodes. You'll see the execution goes in this order. Identation indicates stack depth / how many calls are waiting to be resumed.
getDepth(1)
getDepth(2) // left
getDepth(4) // left
getDepth(null) // left base
getDepth(null) // right base
return 0
getDepth(5) // right
getDepth(null) // left base
getDepth(null) // right base
return 0
return 0 + 1;
getDepth(3) // right
getDepth(6) // left
getDepth(null) // left base
getDepth(null) // right base
return 0
getDepth(7) // right
getDepth(null) // left base
getDepth(null) // right base
return 0
return 0 + 1;
return 1 + 1;
return 2 + 1;
Try to trace the execution if the tree consisted of only a single node (just the root node).
The stack would look something like this when getDepth(root.left) is called:
--->getDepth(root.left) //this will return 0 immediately, and will be popped of the stack
getDepth(root) // this is your entry point
once, getDepth(root.left) returns, the stack looks like this:
--->getDepth(root) // this is your entry point
then the method at the top of the stack now will continue it's execution from where it was (it will now call getDepth(root.right), and the stack will look like this:
--->getDepth(root.right) //this will return 0 immediately, and will be popped of the stack
getDepth(root) // this is your entry point
again, once getDepth(root.right) returns, it will be popped off the stack and the calling method will continue it's execution and will then execute the last if statement.
The same pattern of execution will be followed for a tree with multiple nodes: eventually the recursive method calls will return (unless there is an exception) and the calling method will continue it's execution from the next statement.
I have a recursive function like this:
public static int h(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
} else {
//variable value is a fixed one.
i = value % 2;
return h(n - h(i) - 1) + h(n - 2);
}
}
Suppose the value of variable value is even at this time.Then if I call the function with h(12) I want to know how the function works?
In this case what I want to happen is evaluate
h(12)=h[12-h(0)-1]+h(10)
=h(11)+h(10)
={h(11-h(0)-1)+h(9)}+{h(10-h(0)-1)+h(8)}
={h(10)+h(9)}+{h(9)+h(8)}
Here when evaluating h(11)+h(10) does the function first finish h(11) and get a value for that before starting with h(n-2) which is this case h(10).
If it first finish h(11) then finally it has to reach n==0 or n==1 case.Then by the time it reaches wouldn't h(n-2) be h(-2) or h(-1).
How can I store the initial function call value of 12 and when it reaches h(n-2) to call as h(10) and then make that part to evaluate as h(8),h(6)..
Each function call stores its own copy of arguments. So, call to h(11) won't change n in the first call (h(12)).
Expressions in Java are evaluated from left to right. This means that the call h(11) would finish before h(10) is called from h(12). However, in this case this is not important, since the result would be the same either way.