Algoritmos y estructuras de datos de Java: recorrido previo en orden posterior y búsqueda y eliminación de árboles binarios

1. Sobre la estructura de árbol

¿Por qué necesita una estructura de datos como un árbol?

Ventajas analíticas del almacenamiento en matriz: el acceso a los elementos mediante subíndices es rápido. Para matrices ordenadas, la búsqueda binaria también se puede utilizar para mejorar la velocidad de recuperación. Desventajas: si desea recuperar un valor específico o insertar un valor (en un orden determinado), se moverá como un todo, lo cual es ineficiente.

Ventajas analíticas del método de almacenamiento encadenado: hasta cierto punto, el método de almacenamiento de matriz está optimizado (por ejemplo, para insertar un nodo numérico, solo necesita vincular el nodo insertado a la lista vinculada, y la eficiencia de eliminación también es muy buena ). Desventaja: al recuperar, la eficiencia sigue siendo baja, por ejemplo (recuperando un cierto valor, debe atravesar desde el nodo principal).

El análisis del método de almacenamiento en árbol puede mejorar la eficiencia del almacenamiento y la lectura de datos. Por ejemplo, el uso de Binary Sort Tree no solo puede garantizar la velocidad de recuperación de datos, sino también la velocidad de inserción, eliminación y modificación de datos.

Términos comunes para árboles (entendidos con diagramas esquemáticos):

nodo nodo
raíz nodo
padre nodo
hijo nodo
hoja (nodo sin nodo hijo)
peso del nodo (valor del nodo)
ruta (la ruta para encontrar el nodo desde el nodo raíz)
capa
subárbol
altura del árbol (número máximo de capas)
bosque: varios niños Los árboles forman el bosque


2. Árbol binario

Hay muchos tipos de árboles, y una forma en la que cada nodo solo puede tener como máximo dos hijos se llama árbol binario. Los nodos secundarios de un árbol binario se dividen en nodos izquierdo y derecho.

Si todos los nodos hoja del árbol binario están en el último nivel, y el número total de nodos = 2^n -1, n es el número de niveles, lo llamamos un árbol binario completo.

Si todos los nodos hoja del árbol binario están en la última capa o en la penúltima capa, y los nodos hoja de la última capa son continuos a la izquierda, y los nodos hoja de la penúltima capa son continuos a la derecha, lo llamamos un árbol binario completo.


3. Caso de código

En el código, implementamos principalmente el recorrido del árbol binario en orden previo, en orden y posterior al pedido, así como también buscamos un nodo en orden previo y posterior, y eliminamos un nodo.

El código toma como ejemplo la construcción del siguiente árbol.

package com.szh.tree;

import java.util.Objects;

/**
 *
 */
//先创建HeroNode结点
class HeroNode {
    private int no;
    private String name;
    private HeroNode left;
    private HeroNode right;

    private static int preNum;
    private static int infixNum;
    private static int postNum;

    public HeroNode(int no, String name) {
        this.no = no;
        this.name = name;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public HeroNode getLeft() {
        return left;
    }

    public void setLeft(HeroNode left) {
        this.left = left;
    }

    public HeroNode getRight() {
        return right;
    }

    public void setRight(HeroNode right) {
        this.right = right;
    }

    @Override
    public String toString() {
        return "HeroNode [no=" + no + ", name=" + name + "]";
    }

    //前序遍历
    public void preOrder() {
        //先输出父结点
        System.out.println(this);
        //递归向左子树前序遍历
        if (this.left != null) {
            this.left.preOrder();
        }
        //递归向右子树前序遍历
        if (this.right != null) {
            this.right.preOrder();
        }
    }

    //中序遍历
    public void infixOrder() {
        //递归向左子树前序遍历
        if (this.left != null) {
            this.left.infixOrder();
        }
        //输出父结点
        System.out.println(this);
        //递归向右子树前序遍历
        if (this.right != null) {
            this.right.infixOrder();
        }
    }

    //后序遍历
    public void postOrder() {
        //递归向左子树前序遍历
        if (this.left != null) {
            this.left.postOrder();
        }
        //递归向右子树前序遍历
        if (this.right != null) {
            this.right.postOrder();
        }
        //输出父结点
        System.out.println(this);
    }

    //前序遍历查找某个结点
    public HeroNode preOrderSearch(int no) {
        System.out.println("进入前序遍历查找,第 " + (++preNum) + " 次....");
        //比较当前结点是不是我们要查找的
        if (this.no == no) {
            return this;
        }
        //1.则判断当前结点的左子节点是否为空,如果不为空,则递归前序查找
        //2.如果左递归前序查找,找到结点,则返回
        HeroNode resNode = null;
        if (this.left != null) {
            resNode = this.left.preOrderSearch(no);
        }
        if (resNode != null) { //说明我们在左子树中找到了
            return resNode;
        }
        //1.左递归前序查找,找到结点,则返回,否继续判断,
        //2.当前的结点的右子节点是否为空,如果不空,则继续向右递归前序查找
        if (this.right != null) {
            resNode = this.right.preOrderSearch(no);
        }
        return resNode;
    }

    //中序遍历查找某个结点
    public HeroNode infixOrderSearch(int no) {
        //判断当前结点的左子节点是否为空,如果不为空,则递归中序查找
        HeroNode resNode = null;
        if (this.left != null) {
            resNode = this.left.infixOrderSearch(no);
        }
        if (resNode != null) { //说明在左子树中找到了
            return resNode;
        }
        System.out.println("进入中序遍历查找,第 " + (++infixNum) + " 次....");
        //比较当前结点是不是我们要查找的
        if (this.no == no) {
            return this;
        }
        //否则继续进行右递归的中序查找
        if (this.right != null) {
            resNode = this.right.infixOrderSearch(no);
        }
        return resNode;
    }

    //后序遍历查找某个结点
    public HeroNode postOrderSearch(int no) {
        //判断当前结点的左子节点是否为空,如果不为空,则递归后序查找
        HeroNode resNode = null;
        if (this.left != null) {
            resNode = this.left.postOrderSearch(no);
        }
        if (resNode != null) { //说明在左子树中找到了
            return resNode;
        }
        //如果左子树没有找到,则向右子树递归进行后序遍历查找
        if (this.right != null) {
            resNode = this.right.postOrderSearch(no);
        }
        if (resNode != null) { //说明在右子树中找到了
            return resNode;
        }
        System.out.println("进入后序遍历查找,第 " + (++postNum) + " 次....");
        //如果左右子树都没有找到,就比较当前结点是不是
        if (this.no == no) {
            return this;
        }
        return resNode;
    }

    //递归删除某个结点 (我们自定义如下规则)
    //1.如果删除的节点是叶子节点,则删除该节点
    //2.如果删除的节点是非叶子节点,则删除该子树
    public void delNode(int no) {
        //因为我们的二叉树是单向的,所以我们是判断当前结点的子结点是否需要删除结点,而不能去判断当前这个结点是不是需要删除结点.
        //如果当前结点的左子结点不为空,并且左子结点 就是要删除结点,就将this.left = null; 并且就返回(结束递归删除)
        if (this.left != null && this.left.no == no) {
            this.left = null;
            return;
        }
        //如果当前结点的右子结点不为空,并且右子结点 就是要删除结点,就将this.right = null; 并且就返回(结束递归删除)
        if (this.right != null && this.right.no == no) {
            this.right = null;
            return;
        }
        //如果最开始的两个判断如果都不满足,则需要向左子树进行递归删除
        if (this.left != null) {
            this.left.delNode(no);
        }
        //如果最开始的两个判断如果都不满足,则需要向右子树进行递归删除
        if (this.right != null) {
            this.right.delNode(no);
        }
    }
}

//定义二叉树
class BinaryTree {
    private HeroNode root;

    public void setRoot(HeroNode root) {
        this.root = root;
    }

    //前序遍历
    public void preOrder() {
        if (this.root != null) {
            this.root.preOrder();
        } else {
            System.out.println("二叉树为空,无法遍历");
        }
    }

    //中序遍历
    public void infixOrder() {
        if (this.root != null) {
            this.root.infixOrder();
        } else {
            System.out.println("二叉树为空,无法遍历");
        }
    }

    //后序遍历
    public void postOrder() {
        if (this.root != null) {
            this.root.postOrder();
        } else {
            System.out.println("二叉树为空,无法遍历");
        }
    }

    //前序遍历查找某个结点
    public HeroNode preOrderSearch(int no) {
        if (root != null) {
            return root.preOrderSearch(no);
        }
        return null;
    }

    //中序遍历查找某个结点
    public HeroNode infixOrderSearch(int no) {
        if (root != null) {
            return root.infixOrderSearch(no);
        }
        return null;
    }

    //后序遍历查找某个结点
    public HeroNode postOrderSearch(int no) {
        if (root != null) {
            return root.postOrderSearch(no);
        }
        return null;
    }

    //递归删除某个结点
    public void delNode(int no) {
        if (root != null) {
            //如果该树只有一个root结点, 这里立即判断root是不是就是要删除结点
            if (root.getNo() == no) {
                root = null;
            } else {
                root.delNode(no);
            }
        } else {
            System.out.println("空树,不能删除~~~~");
        }
    }
}

public class BinaryTreeDemo {
    public static void main(String[] args) {
        //先需要创建一颗二叉树
        BinaryTree binaryTree = new BinaryTree();
        //创建需要的结点
        HeroNode root = new HeroNode(1, "宋江");
        HeroNode node2 = new HeroNode(2, "吴用");
        HeroNode node3 = new HeroNode(3, "卢俊义");
        HeroNode node4 = new HeroNode(4, "林冲");
        HeroNode node5 = new HeroNode(5, "关胜");

        //说明,我们先手动创建该二叉树,后面我们使用递归的方式创建二叉树
        root.setLeft(node2);
        root.setRight(node3);
        node3.setRight(node4);
        node3.setLeft(node5);
        binaryTree.setRoot(root);

        //测试前中后序遍历功能
		System.out.println("前序遍历"); // 1,2,3,5,4
		binaryTree.preOrder();
        System.out.println("--------------------------------");
		System.out.println("中序遍历");
        binaryTree.infixOrder(); // 2,1,5,3,4
        System.out.println("--------------------------------");
        System.out.println("后序遍历");
        binaryTree.postOrder(); // 2,5,4,3,1
        System.out.println("=================================================");

        //测试前中后序查找某个结点功能
        System.out.println("前序遍历查找某个结点:");
        HeroNode preNode = binaryTree.preOrderSearch(4);
        if (Objects.nonNull(preNode)) {
            System.out.printf("该结点已找到,信息为 no = %d, name = %s\n", preNode.getNo(), preNode.getName());
        } else {
            System.out.println("查无此人....");
        }
        System.out.println("--------------------------------");
        System.out.println("中序遍历查找某个结点:");
        HeroNode infixNode = binaryTree.infixOrderSearch(4);
        if (Objects.nonNull(infixNode)) {
            System.out.printf("该结点已找到,信息为 no = %d, name = %s\n", infixNode.getNo(), infixNode.getName());
        } else {
            System.out.println("查无此人....");
        }
        System.out.println("--------------------------------");
        System.out.println("后序遍历查找某个结点:");
        HeroNode postNode = binaryTree.postOrderSearch(4);
        if (Objects.nonNull(postNode)) {
            System.out.printf("该结点已找到,信息为 no = %d, name = %s\n", postNode.getNo(), postNode.getName());
        } else {
            System.out.println("查无此人....");
        }
        System.out.println("=================================================");

        //测试删除某个结点功能
        System.out.println("删除之前,前序遍历:");
        binaryTree.preOrder();
        binaryTree.delNode(5);
        System.out.println("删除之后,前序遍历:");
        binaryTree.preOrder();
    }
}

 

Supongo que te gusta

Origin blog.csdn.net/weixin_43823808/article/details/123639822
Recomendado
Clasificación