[tlinh2110@gmail.com] BAEL1377 - Recursion in Java (#3130)
* [tlinh2110@gmail.com] BAEL1377 - Recursion in Java * [BAEL1377] Remove unused method * [tlinh2110@gmail.com] Add sum method * [tlinh2110@gmail.com] Add example for iterative approach
This commit is contained in:
committed by
Grzegorz Piwowarek
parent
327719e1bb
commit
058525f68b
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.recursion;
|
||||
|
||||
public class BinaryNode {
|
||||
int value;
|
||||
BinaryNode left;
|
||||
BinaryNode right;
|
||||
|
||||
public BinaryNode(int value){
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public int getValue() {
|
||||
return value;
|
||||
}
|
||||
public void setValue(int value) {
|
||||
this.value = value;
|
||||
}
|
||||
public BinaryNode getLeft() {
|
||||
return left;
|
||||
}
|
||||
public void setLeft(BinaryNode left) {
|
||||
this.left = left;
|
||||
}
|
||||
public BinaryNode getRight() {
|
||||
return right;
|
||||
}
|
||||
public void setRight(BinaryNode right) {
|
||||
this.right = right;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.baeldung.recursion;
|
||||
|
||||
public class RecursionExample {
|
||||
|
||||
public int sum(int n){
|
||||
if (n >= 1){
|
||||
return sum(n - 1) + n;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
public int tailSum(int currentSum, int n){
|
||||
if (n <= 1) {
|
||||
return currentSum + n;
|
||||
}
|
||||
return tailSum(currentSum + n, n - 1);
|
||||
}
|
||||
|
||||
public int iterativeSum(int n){
|
||||
int sum = 0;
|
||||
if(n < 0){
|
||||
return -1;
|
||||
}
|
||||
for(int i=0; i<=n; i++){
|
||||
sum += i;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
public int powerOf10(int n){
|
||||
if (n == 0){
|
||||
return 1;
|
||||
}
|
||||
return powerOf10(n-1)*10;
|
||||
}
|
||||
|
||||
public int fibonacci(int n){
|
||||
if (n <=1 ){
|
||||
return n;
|
||||
}
|
||||
return fibonacci(n-1) + fibonacci(n-2);
|
||||
}
|
||||
|
||||
public String toBinary(int n){
|
||||
if (n <= 1 ){
|
||||
return String.valueOf(n);
|
||||
}
|
||||
return toBinary(n / 2) + String.valueOf(n % 2);
|
||||
}
|
||||
|
||||
public int calculateTreeHeight(BinaryNode root){
|
||||
if (root!= null){
|
||||
if (root.getLeft() != null || root.getRight() != null){
|
||||
return 1 + max(calculateTreeHeight(root.left) , calculateTreeHeight(root.right));
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
public int max(int a,int b){
|
||||
return a>b ? a:b;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user