Skip to content

Instantly share code, notes, and snippets.

@gdacciaro
Last active February 14, 2019 11:27
Show Gist options
  • Save gdacciaro/7906bc8122b1f8574c68e68f95a33d64 to your computer and use it in GitHub Desktop.
Save gdacciaro/7906bc8122b1f8574c68e68f95a33d64 to your computer and use it in GitHub Desktop.
Traccia del 24/01/2019. NB. Ho considerato la funzione best(a,b,k) come una funzione che restituisce il minimo tra i tre valori in input.
public Integer iterativo(Nodo root, int k){
Stack<Nodo> ST = new Stack<>();
Stack<Integer> Sa = new Stack<>();
Nodo CT = root;
Nodo LT = null;
Integer ret = null;
Integer a = null, b = null;
while(CT!=null || !ST.isEmpty()){
if(CT!=null){
if(CT.k>k){
LT = CT;
ST.push(CT);
CT = CT.sx;
}else if(CT.k<k){
a = CT.k;
Sa.push(a);
LT = CT;
ST.push(CT);
CT = CT.dx;
}else{
LT = CT;
ST.push(CT);
CT = CT.sx;
}
}else{
CT = ST.peek();
if(CT.k>k){
a = ret;
b = CT.k;
ret = best(a, b, k);
ST.pop();
LT=CT;
CT=null;
}else if(CT.k<k){
a = Sa.pop();
b = ret;
ret = best(a, b, k);
ST.pop();
LT=CT;
CT=null;
}else{
if(LT!=CT.dx && CT.dx!=null){ //Risalgo da sinistra e posso andare a destra
a = ret;
Sa.push(a);
CT = CT.dx;
}else {
if (CT.dx == null) { //Risalgo da sinistra e NON posso andare a destra
a=ret;
b=null;
}else { //Risalgo da destra
a = Sa.pop();
b = ret;
}
ret = best(a, b, k);
ST.pop();
LT=CT;
CT=null;
}
}
}
}
return ret;
}
public Integer ricorsivo(Nodo root, int k){
Integer a = null;
Integer b = null;
Integer ret = null;
if(root!=null){
if(root.k>k){
a=ricorsivo(root.sx,k);
b=root.k;
}else if(root.k<k){
a=root.k;
b=ricorsivo(root.dx,k);
}else{
a=ricorsivo(root.sx,k);
b=ricorsivo(root.dx,k);
}
ret = best(a,b,k);
}
return ret;
}
private int best(Integer a, Integer b, int k){
if(a==null) a=Integer.MAX_VALUE;
if(b==null) b=Integer.MAX_VALUE;
int ret = Math.min(a,b);
return Math.min(ret,k);
}
public class Nodo {
public int k;
public Nodo sx;
public Nodo dx;
public Nodo(int k, Nodo sx, Nodo dx) {
this.k = k;
this.sx = sx;
this.dx = dx;
}
public Nodo() {}
public int getK() {
return k;
}
public void setK(int k) {
this.k = k;
}
public Nodo getSx() {
return sx;
}
public void setSx(Nodo sx) {
this.sx = sx;
}
public Nodo getDx() {
return dx;
}
public void setDx(Nodo dx) {
this.dx = dx;
}
@Override
public String toString() {
return "Nodo{" +
"k=" + k +
", sx=" + sx +
", dx=" + dx +
'}';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment