实现二叉排序树的增,删和便利算法
package com.example.admin.myapplication.tree; /** * 二叉排序树 * Created by admin on 2017/11/16. */ public class OrderTree { public static class Node { int value; Node leftChild; Node rightChild; Node parent; public Node(int value) { this.value = value; } } /** * 根节点 */ public Node root; /** * 中序遍历 * * @param root */ public void sortMiddleOrder(Node root) { if (root == null) { return; } sortMiddleOrder(root.leftChild); System.out.println(root.value); sortMiddleOrder(root.rightChild); } /** * 删除 * * @param value * @return */ public Node delete(int value) { System.out.println("删除节点:" + value); Node node = search(value); if (node == null) { return null; } //第一步,找到要删除节点的最小孩子(以下简称替换节点) Node minChild = findMinChild(node); Node parent = node.parent; if (minChild.value == node.value) {//要删除节点没有右孩子 //第二步,删除节点父节点指向替换节点左孩子 if (parent == null) { root = minChild.leftChild; } else if (value > parent.value) { parent.rightChild = minChild.leftChild; } else if (value < parent.value) { parent.leftChild = minChild.leftChild; } } else {//要删除节点有右孩子 //第二步,替换节点的父节点指向替换节点的又孩子 if (minChild.value > minChild.parent.value) { minChild.parent.rightChild = minChild.rightChild; } else { minChild.parent.leftChild = minChild.rightChild; } if (minChild.rightChild != null) { minChild.rightChild.parent = minChild.parent; } //第三步,删除节点父节点指向替换节点 if (parent == null) { root = minChild; } else if (value > parent.value) { parent.rightChild = minChild; } else if (value < parent.value) { parent.leftChild = minChild; } minChild.parent = parent; //第四步,替换节点指向删除节点的左右孩子 minChild.leftChild = node.leftChild; minChild.rightChild = node.rightChild; } return node; } /** * 找到删除节点又孩子最小节点 * * @param root * @return */ private Node findMinChild(Node root) { Node rightChild = root.rightChild; if (rightChild == null) { return root; } root = rightChild; while (root.leftChild != null) { root = root.leftChild; } return root; } /** * 查找 * * @param value * @return */ public Node search(int value) { if (root == null) { return null; } Node node = root; for (; node != null; ) { if (value > node.value) { node = node.rightChild; } else if (value < node.value) { node = node.leftChild; } else { return node; } } return null; } /** * 添加 * * @param node */ public void add(Node node) { Node parent = getParent(node); if (parent == null) { root = node; return; } node.parent = parent; if (node.value > parent.value) { parent.rightChild = node; } else if (node.value < parent.value) { parent.leftChild = node; } } /** * 找到父节点 * * @param node * @return */ private Node getParent(Node node) { Node parent = root; if (parent == null) { return null; } for (; parent != null; ) { if (node.value > parent.value) { if (parent.rightChild != null) { parent = parent.rightChild; } else { break; } } else if (node.value < parent.value) { if (parent.leftChild != null) { parent = parent.leftChild; } else { break; } } else { parent = node; break; } } return parent; } }