Return the second largest element of a binary tree

Asked

Viewed 116 times

0

I am having trouble creating a method that returns the second largest element of a tree. My return code the largest element was like this:

    public int maiorElemento () {
        return maiorElemento(raiz);
    }

    private int maiorElemento(No i) {
        int maior=i.elemento;

        if(i.dir!=null) { 
            maior=maiorElemento(i.dir);
        }

        return maior;
    }

I think my difficulty in creating is: in case the largest is i.dir and there is for example the element i.esq.dir (which would be the second largest).

  • Welcome Stenio, so we can run and bring a better answer it is interesting that you put more details of your code.

  • Where is the i.esq.dir in your code?

  • Post the full code, this way no help

1 answer

0

I did it one way and tested it a few times and got it. But I still feel that something is missing hahah. Follow code:

    public int segundoMaior () {
        return segundoMaior(raiz);
    }

    private int segundoMaior(No i) {

        int segMaior=i.elemento;

        if (i.dir!=null ) {
            if(i.dir.dir!=null) {   
                 segMaior=segundoMaior(i.dir);

            } else if (i.dir.esq!=null) {
                segMaior=segundoMaior(i.dir.esq);
            }
        }


        return segMaior;      
    }
  • If you can post the full code !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.