1.我的代码:
public class BinarySearchTree {class TreeNode {public int key;public TreeNode left;public TreeNode right;public TreeNode(int key) {this.key = key;}}public TreeNode root; // 根节点// 插入一个元素,注意,不能插入重复的值,如果这样,插入失败public boolean insert(int key) {TreeNode newNode = new TreeNode(key);if (this.root == null) {this.root = newNode;return true;}TreeNode parent = null;TreeNode cur = this.root;while (cur != null) {if (key == cur.key) {return false;} else if (key < cur.key) {parent = cur;cur = cur.left;} else {parent = cur;cur = cur.right;}}if (key < parent.key) {parent.left = newNode;} else {parent.right = newNode;}return true;}// 查找key是否存在public TreeNode search(int key) {if (this.root == null) {return null;}TreeNode cur = this.root;while (cur != null) {if (key == cur.key) {return cur;} else if (key < cur.key) {cur = cur.left;} else {cur = cur.right;}}return null;}// 删除key的值public boolean removeTreeNode(int key) {if (this.root == null) {return false;}TreeNode parent = null;TreeNode cur = this.root;while (cur != null) {if (key == cur.key) {this.remove(parent, cur);return true;} else if (key < cur.key) {parent = cur;cur = cur.left;} else {parent = cur;cur = cur.right;}}return false;}private void remove(TreeNode parent, TreeNode cur) {// 分三种大情况// 1.该节点左边为空if (cur.left == null) {// 三种小情况if (cur == this.root) {this.root = cur.right;} else if (cur == parent.left) {parent.left = cur.right;} else { // cur == parent.rightparent.right = cur.right;}} else if (cur.right == null) { // 2.右边为空// 三种小情况if (cur == this.root) {this.root = cur.left;} else if (cur == parent.left) {parent.left = cur.left;} else { // cur == parent.rightparent.right = cur.left;}} else {// 3.左右都不空,使用替罪羊法,找右边最小的替代,然后删除该替代TreeNode tmpParent = cur;TreeNode tmpCur = cur.right;while (tmpCur.left != null) {tmpParent = tmpCur;tmpCur = tmpCur.left;}cur.key = tmpCur.key;// 考虑特殊情况,没有进while循环if (cur == tmpParent) {cur.right = tmpCur.right;} else {tmpParent.left = tmpCur.right;}}}}
public class Test {public static void main(String[] args) {BinarySearchTree binarySearchTree = new BinarySearchTree();int[] array = {12, 4, 5, 10, 8, 3};for (int x : array) {binarySearchTree.insert(x);}binarySearchTree.removeTreeNode(5);}
}
重点研究删除问题,见以上代码.