4
Friends I’m having trouble solving this exercise, and I don’t know how else to do it. I even implemented the tree with recursiveness, but I couldn’t leave the NODE empty and some leaves with number, according to the exercise. Then I need to add up the items that are on the leaves.
In java.
public class No {
public int valor;
public No direito;
public No esquerdo;
public No(int valor) {
this.valor = valor;
}
}
Arvorebinaria.java
public class ArvoreBinaria {
private No raiz;
public void inserir(int valor) {
if (raiz == null) {
raiz = new No(valor);
} else {
No novo = new No(valor);
inserir(raiz, novo);
}
}
private void inserir(No arvore, No novo) {
if (novo.valor > arvore.valor) {
if (arvore.direito == null) {
arvore.direito = novo;
} else {
inserir(arvore.direito, novo);
}
} else {
if (arvore.esquerdo == null) {
arvore.esquerdo = novo;
} else {
inserir(arvore.esquerdo, novo);
}
}
}
EXERCISE
- Uma árvore tem nós; - Um nó pode ou não ter outros nós; - Um nó, não folha, tem sempre um nó do lado direito e outro do lado esquerdo - As folhas não tem nós abaixo; - As folhas têm associado um número inteiro
The following figure represents 3 instances of binary trees
It is intended to implement an algorithm in Java that allows the construction of an instance of this type. You must have a method that returns the sum of the tree, that is the sum of the leaves.
Tips:
- A knot, not a leaf, always has a left knot and a right knot
- After constructing a node, it will be possible to add other nodes
- Recursiveness
- Do not use Java complex type (
HashMap
s,List
s and etc)
@Slinkey99 If this answer solved your problem and you have no questions left, mark it as accepted/correct by clicking on " " here on the side, which also marks your question as answered/solved. If on the other hand you are not yet satisfied, leave a comment and we will clarify.
– Victor Stafusa
Hello Victor, thank you for your help. ? and also the two points : Could you translate please. That’s what? What can I study to learn this? Thank you. public int soma() { Return value + (right == null ? 0 : right.sum()) + (left == null ? 0 : left.sum()); }
– Slinkey99
@Slinkey99 is the ternary operator. If what is before the
?
is true, so the result is what’s between the?
and the:
. If it is false, the result is what is after the:
.– Victor Stafusa
I’ll take a look at it, had not used before. Thank you.
– Slinkey99
@Victorstafusa, from what I understand, you’re taking into account all the nodes in the sum, when the request was just sum of the leaves. I would say that the final sum should have been 32. The correction would be the method
public int somaFolhas() { return (esquerdo == null && direito == null)? valor: ((esquerdo != null? esquerdo.somaFolha():0) + (direito != null? direito.somaFolha(): 0); }
– Jefferson Quesado