Sum values in binary tree of integers weighted by depth - java

Here is my reference tree:
3
/ \
5 2
/ / \
1 4 6
Here is the expected output of the recursive method:
(1*3) + (2 * (5 + 2)) + (3 * (1 + 4 + 6)) = 50
...and here is the code I have thus far:
public int depthSum()
{
int depth = 1;
return depthSum(overallRoot, depth);
}
public int depthSum(IntTreeNode someNode, int someDepth)
{
if(someNode == null)
{
return 0;
}
else
{
return someDepth * someNode.data + //some recursion
}
}
I get that I have to likely call myself and increment someDepth, but I can't seem to get this right. Any ideas?

Presumably you mean:
return someDepth * someNode.data +
depthSum(someNode.left, someDepth+1) +
depthSum(someNode.right, someDepth+1);

Related

Converting to base 10 in java?

I have a homework assignment where I have to covert any base to base 10. I have some given numbers, which are the "basen". I have to convert those bases to base 10. The only part that I am stuck in is this part of the code:
answer = ; // Not sure what I have to put in here
I have seen some other posts about converting to base ten, but I am just not sure how to how to incorporate them into my code.
public class BaseN {
public static final int BASEN_ERRNO = -1;
public static int digit = 0;
public static void main(String[] argv) {
basen(512, 6);
basen(314, 8);
basen(49, 5);
basen(10101, 2);
}
public static void basen(int n, int b) {
int ans = basen(n, b, 1, 0);
if (ans == BASEN_ERRNO)
System.out.println(n + " is not a valid base-" + b + " number");
else
System.out.println(n + " base-" + b + " = " + ans + " base-10");
}
public static int basen(int number, int base, int placevalue, int answer) {
if (number == 0) return answer;
digit = number % 10;
if (digit >= base) return BASEN_ERRNO;
answer = 1;// not sure what to put here
number = 0;
placevalue = 0;
return basen(number, base, placevalue, answer);
}
}
You could look at a k length number of base n like this:
x(0)*n^(k-1) + x(1)*n^(k-2) + ... + x(k-1)*n^1 + x(k)*n^0
Where x(0), x(1), ..., x(k) is the digit at position k from the left.
So, if you are trying to convert, say, 101 base 2 to base 10 you would do the following :
1 * 2^2 + 0 * 2^1 + 1 * 2^0 = 4 + 0 + 1 = 5 base 10
say you want to convert the number 352 from base 6:
3 * 6^2 + 5 * 6^1 + 2 * 6^0 = 108 + 30 + 2 = 145 base 10
What you're looking for code wise is something like this :
int[] digits = {3, 5, 2};
int base = 6;
int answer = 0;
for(int i = digits.length - 1; i >= 0; i--)
{
answer += digits[i] * Math.pow(base,digits.length-i-1);
}
return answer;
which will return 145.
Hopefully even though my implementation is iterative you should be able to apply it to your recursive implementation as well.
You can implement the following algorithm. Lets say you are given String number which represents the number you want to convert to decimal form and int base which represents the base of given number. You can implement function int convertToNumber(char c); which accepts one character representing one digit from your number and will map characters to numbers like this:
0 -> 0,
1 -> 1,
... ,
A-> 10,
B -> 11,
... ,
F -> 15,
...
Then you just iterate through your given string and multiply this functions output with base to the power of iteration. For example, convert number A32(hexadecimal):
A32 = convertToNumber(A) * b ^ 2 + convertToNumber(3) * b ^ 1 + convertToNumber(2) * b ^ 0 = 10 * 16 ^ 2 + 3 * 16 ^ 1 + 2 * 16 ^ 0 = 10 * 16 * 16 + 3 * 16 + 2 = 2610 (decimal).
public class BaseConvert {
public static int convertDigitToNumber(char c) throws Exception {
if(c >= '0' && c <= '9') return c - '0';
if(c >= 'A' && c <= 'Z') return c - 55;
if(c >= 'a' && c <= 'z') return c - 97;
throw new Exception("Invalid digit!");
}
public static int convertToBase(String number, int base) throws Exception {
int result = 0;
for(int i = 0; i < number.length(); i++){
result += convertDigitToNumber(number.charAt(i)) * (int)Math.pow(base, number.length() - i - 1);
}
return result;
}
public static void main(String[] args) {
try{
System.out.println(convertToBase("732", 8));
System.out.println(convertToBase("A32", 16));
System.out.println(convertToBase("1010", 2));
}catch (Exception e) {
System.out.print(e);
}
}
}

Recursion - explanation how the code works (drawing)

i write this code and i try to understand all activities performed (recursive).
Can anyone help me with this draw me up a tree in memory of what happens?
public static String row(int n) {
if (n == 1)
return "1";
else
return row(n - 1) + " " + n;
}
public static String triangle(int a, int b) {
if (a == b)
return row(b);
else
return row(a) + "\n" + triangle(a + 1, b);
}
}
thank's
Your row method:
public static String row(int n) {
if (n == 1) {
return "1";
} else {
return row(n - 1) + " " + n;
}
}
Returns a String containing all the numbers from 1 - n separated by spaces. E.g.row(4) will return a string "1 2 3 4".
Your triangle method prints one row for each row of a triangle.
public static String triangle(int a, int b) {
if (a == b) {
return row(b);
} else {
return row(a) + "\n" + triangle(a + 1, b);
}
}
creates one row of a triangle for each step of row from a up to b.
e.g. triangle(4,6) will print:
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
How the code works
The row method, if given the value 1 will return "1". Any other value will result in a string equivalent to row(n-1) followed by n so essentially it will return 1 2 3 ... n.
The triangle method returns a string which attempts to draw a triangle with numbers. Thus triangle(4,6) returns row(4) + triangle(5,6) which returns row(5) + triangle(6,6) which will returns row(6). Thus the final result will be:
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6

Python error converted from a Java code

I am trying to learn python. So, I have a following Java code to print the list of the factors of the entered number. I am trying to implement the same logic in python. But getting some errors. The java code is as follows:
public final class PrintFactors {
private PrintFactors() {}
public static void printFactors(int number) {
if (number <= 0) throw new IllegalArgumentException("The number should be greater than 0.");
printFactorsList(number, number + "*" + 1 + "\n", number);
}
private static void printFactorsList(int dividend, String factorString, int prevDivisor) {
for (int divisor = dividend - 1; divisor >= 2; divisor--) {
if (dividend % divisor != 0)
continue;
if (divisor > prevDivisor)
continue;
int quotient = dividend / divisor;
if (quotient <= divisor) {
if (quotient <= prevDivisor) {
System.out.println(factorString + divisor + "*" + quotient);
}
}
printFactorsList(quotient, factorString + divisor + "*", divisor);
}
}
public static void main(String[] args) {
printFactors(12);
System.out.println();
printFactors(32);
}
}
The above code outputs the result as follows:
$ java -cp . PrintFactors 32
32 * 1
16 * 2
8 * 4
8 * 2 * 2
4 * 4 * 2
4 * 2 * 2 * 2
2 * 2 * 2 * 2 * 2
My python code is as follows:
def print_factors_list(dividend, factorstring, predivisor):
divisor = dividend - 1
for i in range(int(divisor), 2, -1 ):
if dividend % i != 0:
continue
if divisor > predivisor:
continue
quotient = dividend / divisor
if quotient <= divisor:
if quotient <= predivisor:
print factorstring + str(divisor) + "*" + str(quotient)
print_factors_list(quotient, str(factorstring) + str(divisor) + "*", divisor)
def print_factors(x):
if (x < 0):
print "Enter a positive interger"
else:
print_factors_list(x, str(x) + "*" + str(1) + "\n", x )
num = int(input("Enter a number: "))
print_factors(num)
I am getting the following error:
undefined: Error: local variable 'quotient' referenced before assignment
Please can someone help me with this where am I going wrong. Is there a logic error as I have implemented the steps as the Java code? Thanks.
Python is indentation-sensitive. You had your print_factors_list recursive call at the outermost indentation level, thus it's outside of the for loop. This is different behaviour from your Java code.

Binary Tree diff of sum of nodes at odd and sum of nodes at even

How can I write the function to return the difference of the sum of values of nodes at odd height and the sum of values of nodes at even height. Considering the root node is at height 1 for a binary tree
input:
1
2 3
4 5 6 7
8 9 10 11 12 13 14 15
Output: -74 Explanation :
[ (1 + 4 + 5 + 6 + 7 ) - (2 + 3 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15) = -74 ]
Code:
public static int diff(Node n) {
if (n == null)
return 0;
return Sum(n) - Sum(n.left) - Sum(n.right);
}
public static int Sum(Node root) {
int sum = 0;
if (root == null) {
return sum;
}
sum = sum + root.data;
if (root.left != null) {
sum = sum + Sum(root.left.left) + Sum(root.left.right);
}
if (root.right != null) {
sum = sum + Sum(root.right.left) + Sum(root.right.right);
}
return sum;
}
I have given this solution but not selected... I don't know whats wrong with this.
public static int Sum(Node root) {
if (root == null) {
return 0;
}
return root.data-Sum(root.left)-Sum(root.right);
}
This is easiest and smartest way i found the solution
Here solution is explained using recusrsion in short..
Negate all levels under the current one (the level of the current node) and you do that on each step of the recursion.
sum[l1] – (sum[l2] – (sum[l3] – (sum[l4] – … = sum[l1] – sum[l2] + sum[l3] – sum[l4]…
www.crazyforcode.com/binary-tree-diff-sum-even-nodes-sum-odd-nodes/
How about...
public static int diff(Node n) {
return sumtree(Node n, 1);
}
public static int sumtree(Node n, int level) {
if (n == null) return 0;
if (level % 2 == 0) {
return sumtree(n.left, level + 1) + sumtree(n.right, level +1 ) - n.value;
} else {
return sumtree(n.left, level + 1) + sumtree(n.right, level + 1) + n.value;
}
}
Add values on odd level numbers (1, 3, 5 7...), subtract on even (2, 4, 6, 8...).
The approach I took was to first find a way of adding all of the leaves, then just add a "level factor" if the level is even you you add otherwise you subtract. This may look similar to others but I find it cleaner.
On ANSI C
int diffOddAndEven(Node *root)
{
return sumLevel(root, 0);
}
int sumLevel(Node *root, int level)
{
int sum=0;
int levelFactor = level%2 ? -1 : 1;
if(!root)
return 0;
sum = root->value * levelFactor;
sum += sumLevel(root->left, level+1);
sum += sumLevel(root->right, level+1);
return sum;
}
Check out my solution
traverse(root,1); //1 is passed since we want oddlevelsum - evenlevelsum,pass -1 for opposite
int traverse(Tree* root,int level){
if(root==NULL)return 0;
return (level*root->data)+ traverse(level*-1,root->left_node)
+ traverse(level*-1,root->right_node);
}

Simple Recursion Explanation

Here is a recursive static method in Java.
public static int mystery(int m, int n) {
int result = 1;
if (m > 0) {
result = n * mystery(m-1, n);
}
System.out.println (m + " " + result);
return result;
}
What will be printed to the standard output if we make the method call mystery(3,4)? What would be the final return value from the call to mystery(3,4)?
What is the explanation to the answer for the standard output part.
Output:
0 1
1 4
2 16
3 64
The final return value is 64.
Consider n to be fixed (which for all intents and purposes it is) and let f(m) be mystery(m,n).
Then
f(0) = 1
f(1) = n * f(0) = n
f(2) = n * f(1) = n * n
f(3) = n * f(2) = n * n * n
Can you see the general pattern? Can you give a closed form for f(n)?
Given your code which is
public static int mystery(int m, int n) {
int result = 1;
if (m > 0) {
result = n * mystery(m-1, n);
}
System.out.println (m + " " + result);
return result;
}
Lets start with m = 3 and n = 4, lets try to emulate it by trying to be the debugger...
mystery(3,4){
int result = 1
if(3 > 0){
result = 4 * mystery(3-1,4);
//We proceed from this point only after evaluating mystery(2,4)
mystery(2,4){
int result = 1
if(2 > 0){
result = 4*mystery(2-1,4);
//Now we have to evaluate mystery(1,4)
mystery(1,4){
int result = 1;
if(1 > 0){
result = 4*mystery(1-1,4);
//Evaluate mystery(0,4)
mystery(0,4){
int result = 1;
if(0 > 0){
//Not evaluated
}
System.out.println(0 + " "+1);
return 1;
}...mystery(0,4) done continue with evaluation of mystery(1,4)
result = 4*1 //1 is what is returned by mystery(0,4)
System.out.println(1+ "" + 4);
return 4;
}//done with the evaluation of mystery(1,4), resume evaluation of mystery(2,4)
result = 4*4 //4 is the value returned by mystery(1,4)
System.out.println(2 + " " + 16);
return 16;
}//At this point we are done with evaluating (2,4) and on the way to resume evaluation of mystery(3,4)
result = 4 * 16
System.out.println(3 + " "+ 64)
return 64;
}
}
Hope this helps
This sample calculates m to the power n.
So in your case the value is 64.
However have you tried it out and did analysis on your part?
The first call is mystery(3,4) which then calls mystery(2,4) which then calls mystery(1,4) which then calls mystery(0,4). In this example, the base case is mystery(0,4), i.e. m > 0 evaluates to false and result = n*mystery(m-1,n) will not get executed (recursion terminates here). Your base case is on top of the call stack and the bottom of your stack is mystery(3,4). Evaluate from the top of the call stack towards the bottom…

Categories

Resources