一、排序二叉树(二叉查找树、二叉搜索树)
1、介绍
排序二叉树(Binary Sort Tree),性质:左孩子 < 根结点 < 右孩子。在一般情况下,查询效率比链表要高。
按照中序遍历可以得到一个从小到大的有序序列。
2、创建、添加、删除
创建和添加简单,删除情况比较复杂,有三种情况考虑:
①删除叶子结点(度为0),比如:2,5,9,12。
②删除只有左(右)孩子的结点(度为1),比如:1。
③删除有左(右)孩子的结点(度为2),比如:7,3,10。
删除度为2的结点,方法:取右子树的最小值替换它,且删除这个最小值。比如:删除7,用 7 的右子树最小值 9 替换7。且删除9。
代码示例:排序二叉树创建、添加、删除
1 // 二叉树 2 public class BinaryTree { 3 // 根结点 4 protected TreeNode root; 5 6 /** 7 * 获取树的高度 8 * 9 * @return 10 */ 11 public int getHeight() { 12 return this.getHeight(root); 13 } 14 15 protected int getHeight(TreeNode root) { 16 if (root == null) { 17 return 0; 18 } 19 20 final int left = this.getHeight(root.left); 21 final int right = this.getHeight(root.right); 22 23 return Math.max(left, right) + 1; 24 } 25 26 /** 27 * 获取树的结点数 28 * 29 * @return 30 */ 31 public int getSize() { 32 return this.getSize(root); 33 } 34 35 private int getSize(TreeNode root) { 36 if (root == null) { 37 return 0; 38 } 39 40 final int left = this.getSize(root.left); 41 final int right = this.getSize(root.right); 42 43 return left + right + 1; 44 } 45 46 // 中序遍历 47 public void infixOrder() { 48 this.infixOrder(root); 49 } 50 51 private void infixOrder(TreeNode root) { 52 if (root != null) { 53 this.infixOrder(root.left); 54 System.out.print("-->" + root.value); 55 this.infixOrder(root.right); 56 } 57 } 58 59 /** 60 * 树结点结构 61 */ 62 protected static class TreeNode { 63 public int value; 64 public TreeNode left; 65 public TreeNode right; 66 67 public TreeNode(int value) { 68 this.value = value; 69 } 70 71 // 返回结点的度 72 public int getDegree() { 73 if (this.left == null && this.right == null) { 74 return 0; 75 } 76 77 if ((this.left != null && this.right == null) || (this.left == null && this.right != null)) { 78 return 1; 79 } 80 81 return 2; 82 } 83 84 @Override 85 public String toString() { 86 return "TreeNode{" + 87 "value=" + value + 88 '}'; 89 } 90 } 91 92 }