Java implementa a árvore de pesquisa binária e implementa a pesquisa, insira e exclua operações na árvore (mescla e exclua, copie e exclua)
Primeiro de tudo, precisamos ter uma idéia de codificação, aproximadamente a seguinte:
1. Pesquisa: De acordo com as características dos dados da árvore de pesquisa binária, podemos realizar a pesquisa com base na comparação de valor dos nós. Quando o valor da pesquisa for maior que o nó atual, vá para a direita e vice -versa!
2. Inserir: devemos saber que todos os inseridos são nós de folhas, por isso precisamos encontrar a localização do nó foliar a ser inserido e a ideia de inserção é consistente com a ideia de pesquisa.
3. Exclua:
1) Mesclar e excluir: De um modo geral, as seguintes situações serão encontradas. O nó excluído possui uma subárvore esquerda, mas nenhuma subárvore direita. Neste momento, o nó pai do nó atual deve apontar para a subárvore esquerda do nó atual; Quando o nó excluído tem uma subárvore direita, mas não a subárvore esquerda, o nó pai do nó atual deve apontar para a subárvore direita; Quando o nó excluído tem uma subárvore esquerda e uma subárvore direita, podemos encontrar o nó mais à direita da subárvore esquerda do nó excluído e depois deixar o "ponteiro" do nó direito ou esquerdo para a subárvore direita do nó deleto
2) Cópia e exclusão: cópia e exclusão são operações de exclusão relativamente simples e também são as operações de exclusão mais usadas. Existem aproximadamente três situações: quando o nó atual não tiver subárvore esquerda e tiver uma subárvore direita, deixe o nó raiz da subárvore direita atual substituir o nó excluído; Quando o nó atual não tiver subárvore direita e uma subárvore esquerda, deixe o nó raiz da subárvore esquerda atual e substitua o nó excluído; when the currently deleted node has both a left subtree and a right subtree, we need to find the subtree of the deleted node, and find the rightmost node in the left subtree and assign the value of this node to the deleted node, and then don't forget to let the "pointer" of the parent node pointing to the subtree is empty (in fact, it doesn't matter in Java, and there is a garbage disposal mechanism to automatically processar -o). Você também pode implementar esse processo como um nó independente no nó mais à esquerda da subárvore direita do nó atualmente excluído.
Em seguida, vamos adicionar o código.
Primeiro de tudo, ## Binary Search Tree Node Class ##
PACOTE PARTHBINARYTREE; Public Classe SearchBinaryTreenode <T> {t Data; Public SearchBinaryTreenode <T> Leftchild; Public SearchBinaryTreenode <T> RightChild; public SearchBinaryTreenode () {this.data = null; this.leftchild = this.rightChild = null; } public SearchBinaryTreenode (t Da) {this.data = da; this.leftchild = this.rightChild = null; } public SearchBinaryTreenode (t Da) {this.data = da; this.leftchild = this.rightChild = null; } public SearchBinaryTreenode (T DA, SearchBinaryTreenode <T> Esquerda, SearchBinaryTreenode <T> DIREITA) {this.data = da; this.leftchild = esquerda; this.rightChild = certo; } public t getData () {retornar dados; } public void setData (t data) {this.data = data; } public SearchBinaryTreenode <T> getLeftChild () {return leftChild; } public void SetLeftChild (SearchBinaryTreenode <T> leftChild) {this.leftchild = leftChild; } public SearchBinaryTreenode <T> getRightChild () {return RightChild; } public void SetrightChild (SearchBinaryTreenode <T> RightChild) {this.rightChild = RightChild; } public boolean isleaf () {if (this.leftchild == null && this.rightChild == null) {return true; } retornar false; }}Implementando uma árvore de pesquisa binária
PACOTE PARTHBINARYTREE; Public Classe SearchBinaryTree <T> {SearchBinaryTreenode <T> root; public boolean isEmpty () {if (root == null) {return true; } retornar false; } public void visit (SearchBinaryTreenode <T> root) {if (root == null) {System.out.println ("Esta árvore está vazia!"); } System.out.println (root.getData ()); } public SearchBinaryTreenode <T> getRoot () {if (root == null) {root = new SearchBinaryTreenode <T> (); } retornar root; } public SearchBinaryTree () {this.root = null; } /** Crie uma árvore binária* / public void createTree (SearchBinaryTreenode <T> nó, t data) {if (root == null) {root = new SearchBinaryTreenode <T> (); } else {if (Math.random ()> 0.5) {// Crie uma árvore binária de maneira aleatória se (node.leftchild == null) {node.leftchild = new SearchBinaryTreenode <T> (dados); } else {createTree (node.leftchild, dados); }} else {if (node.rightChild == null) {node.rightChild = new SearchBinaryTreenode <T> (dados); } else {createTree (node.rightChild, dados); }}}}} /** Pesquise na segunda árvore de pesquisa* / public SearchBinaryTreenode <T> Pesquisa (SearchBinaryTreenode <T> root, valor t) {SearchBinaryTreenode <T> current = root; while ((root! = null) && (current.getData ()! = value)) {// Deve -se observar que os genéricos do Java não podem comparar tamanhos. No uso real, podemos usar tipos de dados comuns para substituir esse genérico, para que não haja erros. Atual = (valor <current.getData ()? Pesquisa (current.leftchild, valor): pesquisa (current.rightChild, valor)); } retornar atual; } public SearchBinaryTreenode <T> insertNode (valor t) {SearchBinaryTreenode <T> p = root, pre = null; while (p! = null) {pre = p; // Deve -se notar que os genéricos do Java não podem comparar tamanhos. No uso real, podemos usar tipos de dados comuns para substituir este genérico, para que não haja erros se (p.getData () <value) {p = p.rightChild; } else {p = p.leftchild; }} if (root == null) {root = new SearchBinaryTreenode <T> (valor); } else if (pre.getData () <value) {pre.rightChild = new SearchBinaryTreenode <T> (value); } else {pre.leftchild = new SearchBinaryTreenode <T> (valor); }} /** Mesclar e excluir* / public void DeleteByMerging (SearchBinaryTreenode <T> nó) {SearchBinaryTreenode <T> temp = node; if (node! = null) {// Se o nó excluído não tiver uma subárvore direita, use o nó raiz da subárvore esquerda para substituir o nó excluído se (node.rightChild! = null) {node = node.leftchild; } else if (node.leftchild == null) {// Se o nó excluído não tiver uma subárvore esquerda, use o nó mais à esquerda com a contagem de palavras em vez do nó excluído = node.rightChild; } else {// se as subáridas esquerda e direita dos nós excluídos tiverem temp = node.leftchild; while (temp.rightChild! = null) {temp = temp.rightChild; // A seguir, encontre o nó direito da subárvore esquerda} // atribui o ponteiro direito do nó encontrado à raiz da subárvore direita do nó excluído temp.rightChild = node.rightChild; temp = nó; node = node.leftchild; } temp = null; }} / * * Copie e exclua * / public void DeleteByCoping (SearchBinaryTreenode <T> nó) {SearchBinaryTreenode <T> pre = null; SearchBinaryTreenode <T> temp = node; // Se o nó excluído não tiver uma subárvore direita, use o nó raiz da subárvore esquerda para substituir o nó excluído se (node.rightChild == null) {node = node.leftchild; } else if (node.leftchild == null) {node = node.rightChild; } else {// se as subáridas esquerda e direita dos nós excluídos tiverem temp = node.leftchild; pre = nó; while (temp.rightChild! = null) {pre = temp; temp = temp.rightChild; // viaja para encontrar o nó mais à direita da subárvore esquerda} node.data = temp.data; // Execute a operação de atribuição se (pre == node) {pre.leftchild = node.leftchild; } else {pre.rightChild = node.rightChild; }} temp = null; }}Classe de teste
PACOTE PARTILHAÇÃOBINETREE; Public class SearchBinaryTereTest {public static void main (string [] args) {SearchBinaryTree <Teger> árvore = new SearchBinaryTree <Teger> (); for (int i = 1; i <10; i ++) {Tree.createTree (novo SearchBinaryTreenode <Teger> (), i); } // pesquisa de pesquisa.search (árvore.root, 7); // mesclar e excluir árvore.deletebymerging (novo SearchBinaryTreenode <Teger> (8)); // copiar e excluir árvore.deletebyCoping (novo SearchBinaryTreenode <Teger> (6)); }}OK, é isso!
O artigo acima Java cria uma árvore de pesquisa binária e implementa os exemplos de pesquisa, inserção e exclusão são todo o conteúdo que compartilho com você. Espero que você possa lhe dar uma referência e espero que você possa apoiar mais o wulin.com.