How does this function compute the number of nodes in binary tree - c

I've a function that I'm trying to analyze which its output is 7:
Given this block of code:
int func_1(struct node* node)
{
if (node == NULL)
return 0;
else
return func_1(node->left) + 1 + func_1(node->right);
}
And this Binary Search Tree:
The return value is 7.
I know recursion and it's kinda simple here, I tried to follow up and I can not understand how it returned 7. I calculated that it just goes left, left, then one time right, and that's it. which will return 3. And even if it goes 3 times right, after the root, it will still return 6 and not 7.
Can you guys help me out please?

Semantically it takes the number of left nodes + 1 (the current node) + the number of right nodes.
with func_1(x) I mean calling the function on that specific node.
So the complete calculation is
func_1(8) + 1 + func_1(14)
(func_1(7) + 1 + func_1(9)) + 1 + func_1(14)
(1 + 1 + 1) + 1 + (0 + 1 + func_1(17)
3 + 1 + (0 + 1 + (0 + 1 + func_1(18))
3 + 1 + (1 + (1 + (0 + 1 + 0)
results in 7
This principle is used very often in recursion:
first do the calculation for the 'current' item (the current node), in this case the number of nodes for the 'node itself' is 1.
than add the calculation of the other items in a recursive way, in this case the number of nodes left of the current node, and the number of nodes right of the current node. For ordering reasons in this case the +1 for the current node (number of nodes) is put in the middle.

Take a look at the leaf node 7.
When func_1 is called with the value of the node 7, the if statement will branch into the else part, since the pointer to this node is valid.
Then func_1 will be called twice once for the left child and once for the right child. In both cases the functions return 0, since left and right child are NULL. The function will return 1:
return func_1(node->left) + 1 + func_1(node->right);
equivalent to:
return func_1(NULL) + 1 + func_1(NULL);
becomes:
return 0 + 1 + 0;

Look at this statement
return func_1(node->left) + 1 + func_1(node->right);
^^^^^
if a node is not equal to NULL it counts itself plus the number of nodes in the left and right sub trees relative to this node.
So you will get a result that is equal to the number of nodes that are not equal to NULL.

Related

Additions based on item frequency in an array (Lua)

I have an array which is used to compute a score in a game:
a = {1,7,5,1,2,6,2,3,4,5,5,6,7,7,7}
All numbers should be simply added, except when a number appears several times, for instance 7 (which appears 4 times) it should be added as such:
1*7 + 2*7 + 3*7 + 4*7
So, altogether, array "a" should give this score:
score = (1*1 + 2*1) + (1*2 + 2*2) + (1*3) + (1*4) + (1*5 + 2*5 + 3*5) + (1*6 + 2*6) + (1*7 + 2*7 + 3*7 + 4*7)
I wouldn't know where to start doing this. What's a good method for this kind of calculation?
Any help is appreciated.
You can keep track of the current multiplier for each number in another table:
function calculateScore(a)
local multipliers = {}
local score = 0
for i,number in ipairs(a) do
local multiplier = multipliers[number] or 1
multipliers[number] = multiplier + 1
score = score + number * multiplier
end
return score
end
local a = {1,7,5,1,2,6,2,3,4,5,5,6,7,7,7}
local score = calculateScore(a)

VBA Run-time error 13 - type mismatch- price time series calc not working on array

I suspect my question has a very simple answer, and yet I cannot find an answer that I understand in searching all over the site.
Ticker1 = an array of stock prices (1 to 2542)
PctChg1 = an array which I hope will ultimately hold the results of
(Price_last / Price_prev) - 1
i = counter
Code:
For i = 2 To UBound(Ticker1)
PctChg1(i, 1) = Ticker1(i, 1) / Ticker1(i - 1, 1) - 1
Next i
Something about the Ticker1(i - 1, 1) part it does not like - I have fooled around with ranges as well and cannot make sense of this. I don't know why it thinks I am dividing by a number that isn't there - if i am starting at point 2 of the array, why wouldn't I be able to reference point 1 ?
For i = 2 To UBound(Ticker1)
If Val(Ticker1(i - 1, 1)) <> 0 Then PctChg1(i, 1) = Ticker1(i, 1) / Ticker1(i - 1, 1) - 1
Next i
This works, but I still have not established why i-1 generates errors when I start the calculation on data point i=2.

Problems with Expressions in C

I have two functions written that have simple assignment statements with very simple expressions. The expressions are the same for both functions, however, they involve different variable types: One function uses an array of structs, the other just uses a typedef'd struct.
When running the functions, the second function fails to divide by 256, and I get very high values that are not "normalized". I have to uncomment the second line in the second function (valueB = valueB / 256) to get it to work.
The first function, however, works perfectly.
Heres the statement in Function One:
value = ((p[0].value * p2Area)+(p[1].value * p3Area)+(p[2].value * p0Area)+(p[3].value * p1Area) / 256);
Heres the statement in Function Two:
valueB = ((dataPoints.p0B * p2Area)+(dataPoints.p1B * p3Area)+(dataPoints.p2B * p0Area)+(dataPoints.p3B * p1Area) / 256);
//valueB = valueB / 256;
Why would this happen?
Also, I pass the functions the same numbers and it doesn't seem to help.
This is on MacOSX 10.6.8, inside Xcode 3.2.6
Are you absolutely sure the first one works properly? You have
value = ((p[0].value * p2Area)+(p[1].value * p3Area)+(p[2].value * p0Area)+(p[3].value * p1Area) / 256);
I think you want:
value = (((p[0].value * p2Area)+(p[1].value * p3Area)+(p[2].value * p0Area)+(p[3].value * p1Area)) / 256);
Similar thing with the second. I think it should be:
value = (((p[0].value * p2Area)+(p[1].value * p3Area)+(p[2].value * p0Area)+(p[3].value * p1Area)) / 256);
In both cases I think you want to divide the sum of the products by 256. Not just the last one. My change only involves placing an extra set of parentheses around the sum of the product subexpressions and dividing the entire thing by 256
In all languages there is an order by which mathematical (and all other operators are completed). It just so happens that * and / are higher in precedence than + and - in C/C++ You may refer to this link for more details.
To simplify what happened to you, I will create this simple equation:
2 + 4 + 6 + 4 / 2
Since division occurs first (and there are no parentheses to alter the order) it gets computed as:
2 + 4 + 6 + (4 / 2) = 14
Not:
(2 + 4 + 6 + 4) / 2 = 8
So my change to your code was the same as putting parentheses around 2 + 4 + 6 + 4 / 2 giving (2 + 4 + 6 + 4) / 2 and forcing the division to be done last after all the additions are completed.

Questions related to recursion

Please find the code below which shows some operations based on recursion.I would love some one to please explain me how this recursion works?
#include <stdio.h>
int func(int);
main()
{
int ret = 0;
ret = func(6);
printf("The val is %d\n",ret);
}
int func(int m)
{
if((m==0)||(m==1))
{
return 1;
}
else
{
return (func(m-1)+func(m-2));
}
}
When executed,the value of val is 13.Please someone explain how does this unwind operations happens in stack
You don't need to involve a stack or any unwinding (excuse me for involving myself, though).
Just substitute the call with the content of the function, and keep doing that until you no longer recurse:
ret = func(6) =
func(5) + func(4) =
func(4) + func(3) + func(3) + func(2) =
func(2) + func(3) + func(1) + func(2) + func(1) + func(2) + func(0) + func(1) =
func(0) + func(1) + func(1) + func(2) + 1 + func(0) + func(1) + 1 + func(1) + func(0) + 1 + 1 =
1 + 1 + 1 + func(0) + func(1) + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 =
3 + 1 + 1 + 8 =
3 + 2 + 8 =
13
It's a bit difficult with the typography, but that's what happens and the answer seems to match what you got, too.
Recursion is nothing more than calling the a function from within that particular function. A lot of mathematical algorithms or (tree) search algorithms use this technique for their desired result.
Recursive function calls need to 'escape' their repeating 'self calling' otherwise the application would become unresponsive. In your example, this is done by the if((m==0)||(m==1)) check. If the check is true, the function just returns 1 (and escapes the recursion).
The recursive code you showed calculates the Fibonacci sequence, which is a typical recursive algorithm, as it requires the values of 2 previous calculations. Step 0 and 1 return 1. These 2 values are added for step 2 (resulting in 1+1=2). The next step results in 1+2=3. And so on. As you see this can only be calculated from the start (and thus requires the recursion to do so)
Your program tries to print the nth(or n+1th) number of a Fibonacci series. Here the base case is when m =1 or m=0
The worst thing about recursion here is a value is calculated twice for example func(4), func(3) and func(2) as evident from here.

How does this function count the number of nodes in a tree?

A function to count the number of nodes in a tree.
int count(node *t)
{
int i;
if (t == NULL)
return(0);
i = 1 + count(t->left) + count(t->right); // recursion occurs address of left node is passed and
return(i); // continue to pass until whole left node
} // is traversed and the value of t is
// NULL and 0 is returned same for right node counting
// i = 1 + 0 + 0 = 1
How is the number of nodes counted ?
To understand recursion, you must first understand recursion.
That's a recursive implementation of counting tree nodes. It is called for the root node and returns "one plus number of nodes in left subtree plus number of nodes in the right subtree", that is done recursively until it reaches leaf nodes.
The total count includes the current/root node plus the count on the left branch plus the count on the right branch. Your sentinel is the NULL which means you've reached the leaf node of whatever branch you are currently counting. Then you unwind back up. Recursion :)
First, have you tried it yourself?
Basically, it adds 1 for every non-null node. It's roughly like this: 1 + number_of_nodes_to_the_left + number_of_nodes_to_the_right. This expands to: 1+(1+number_of_nodes_to_the_left_in_left+number_of_nodes_to_the_right_in_left) + (1+number_of_nodes_to_the_left_in_right + number_of_nodes_to_the_right_in_right). Keep on expanding and you'll see that it's basically 1 + 1 + 1 +.... for every non-null node in the tree.
EDIT: To illustrate this better, consider the following tree:
Node0
|
(left) | (right)
Node1 _|_ Node2
|
(left) | (right)
Node3 _|_ Node4
When you do int node_count = count(Node0), since Node0 is not NULL, it goes to the return statement which is:
return 1 + count(left) + count(right). You need to understand a basic thing that very operation in your recursion function happens one-after-the-other.In other words operation count(right) doesn't happen until operation count(left) is completed. Now take a look at the return statement you have there and translate it in terms of the above tree. It would be 1+count(Node1)+count(Node2). So count(Node2) doesn't get calculated before count(Node1) has finished. So for count(Node1), count function gets called (again) with Node1 as the argument. So let us, for now, forget about the semi-calculated expression 1+count(Node1)+count(Node2) (we'll come back to it later).
Now for count(Node1), Node1 is not NULL and hence proceeds to the return statement. This would (again) be 1+count(left)+count(right). But wait, Node1 doesn't have left and right nodes. So, when count(left) gets called with the argument being NULL, it returns 0 and the same happens for count(right). So the expression for count(Node1) becomes 1 + 0 + 0. There are no more count functions being called for Node1 and hence it returns to it's original caller, which was the return statement of count(Node0).
Since we have count(Node1) figured out, let's replace it in the return statement of count(Node0). This now becomes 1 + (1 + 0 + 0) + count(Node2).
Now I'm going to make this a bit faster. Since Node2 has two children, the return statement of Node2 will be 1 + count(Node3) + count(Node4). Just like it was for Node1, count(Node3) and count(Node4) will each return 1 + 0 + 0, turning the return statement of count(Node2) to be 1 + (1 + 0 + 0) + (1 + 0 + 0).
Now that count(Node2) has been fully calculated, let's return to the original caller of count(Node2), which is 1 + (1 + 0 + 0) + count(Node2). Replace what we got from count(Node2) in there and we get 1 + (1+0+0) + (1 + (1+0+0) + (1+0+0)). Add it up and we get the value of 5. This value gets returned to whichever function that called count(Node0), like the statement int node_count = count(Node0) and node_count will have the value 5.
Consider these trees:
A tree with no nodes (i.e. a NULL pointer) - returns 0
A tree with one node, the root. This will call:
i=1+count(t->left)+count(t->right);
with left and right NULL, and so will return 1 + 0 + 0
A tree with a root and a single right leaf
i=1+count(t->left)+count(t->right);
will return 1 for the root, 0 for the tree rooted at left (by the rules above) and 1 for the tree rooted at right (by the rules above), which is 1 + 0 + 1
And so on.

Resources