1 package iYou.neugle.search; 2 3 public class BSTree_search { 4 class BSTree { 5 public int data; 6 public BSTree left; 7 public BSTree right; 8 } 9 10 public static void main(String[] args) { 11 BSTree_search bst = new BSTree_search(); 12 int[] array = new int[] { 50, 30, 70, 10, 40, 90, 80 }; 13 BSTree bsTree = bst.CreateBSTree(array); 14 15 bst.LDR_BST(bsTree); 16 17 boolean bool = bst.SearchBSTree(bsTree, 10); 18 System.out.println("10是否在二叉排序树中:" + bool); 19 20 BSTree adjustBSTree = bst.DeleteBSTree(bsTree, 50); 21 bst.LDR_BST(adjustBSTree); 22 } 23 24 // 创建二叉排序树 25 public BSTree CreateBSTree(int[] array) { 26 BSTree bsTree = null; 27 for (int i = 0; i < array.length; i++) { 28 if (bsTree == null) { 29 bsTree = new BSTree(); 30 bsTree.data = array[i]; 31 } else { 32 this.InsertBSTree(bsTree, array[i]); 33 } 34 } 35 return bsTree; 36 } 37 38 // 递归创建左右子树 39 public void InsertBSTree(BSTree bsTree, int key) { 40 if (bsTree.data > key) { 41 if (bsTree.left == null) { 42 bsTree.left = new BSTree(); 43 bsTree.left.data = key; 44 } else { 45 InsertBSTree(bsTree.left, key); 46 } 47 } else { 48 if (bsTree.right == null) { 49 bsTree.right = new BSTree(); 50 bsTree.right.data = key; 51 } else { 52 InsertBSTree(bsTree.right, key); 53 } 54 } 55 } 56 57 // 中序遍历(递归) 58 public void LDR_BST(BSTree bsTree) { 59 if (bsTree != null) { 60 LDR_BST(bsTree.left); 61 System.out.println(bsTree.data); 62 LDR_BST(bsTree.right); 63 } 64 } 65 66 // 在二叉排序树中查找元素是否存在 67 public boolean SearchBSTree(BSTree bsTree, int key) { 68 if (bsTree == null) { 69 return false; 70 } 71 if (bsTree.data == key) { 72 return true; 73 } 74 if (bsTree.data > key) { 75 return SearchBSTree(bsTree.left, key); 76 } else { 77 return SearchBSTree(bsTree.right, key); 78 } 79 } 80 81 // 删除二叉排序树中的节点 82 public BSTree DeleteBSTree(BSTree bsTree, int key) { 83 if (bsTree == null) { 84 return null; 85 } 86 87 if (bsTree.data == key) { 88 // 第一种情况:叶子节点 89 if (bsTree.left == null && bsTree.right == null) { 90 bsTree = null; 91 } 92 // 第二种情况:节点有左子结点 93 if (bsTree.left != null && bsTree.right == null) { 94 bsTree = bsTree.left; 95 } 96 // 第三种情况:节点有右子结点 97 if (bsTree.left == null && bsTree.right != null) { 98 bsTree = bsTree.right; 99 } 100 // 第四种情况:节点既有左子结点又有右子结点 101 if (bsTree.left != null && bsTree.right != null) { 102 BSTree temp = bsTree.right; 103 // 查找到右边节点中最左侧的节点 104 while (temp.left != null) { 105 temp = temp.left; 106 } 107 // 将左边节点赋给右边节点中最左侧的节点 108 temp.left = bsTree.left; 109 110 bsTree = bsTree.right; 111 } 112 113 return bsTree; 114 } 115 116 if (bsTree.data > key) { 117 bsTree.left = DeleteBSTree(bsTree.left, key); 118 } else { 119 bsTree.right = DeleteBSTree(bsTree.right, key); 120 } 121 122 return bsTree; 123 } 124 }
时间: 2024-10-22 16:25:55