BST
1.二叉树的特性
1.对于一个二叉树的节点来说,它的值大于它的左子树所有节点的值,小于它的右子树所有节点的值;
2.二叉搜索树的中序遍历是有序集合。
2.对二叉搜索树的操作
1.查找:
1)采用递归的方式从根节点查找,小于往左,大于往右
TreeNode BSTsearch(TreeNode root, int val){
if(root == null) return null;
if(root.val < val) return BSTsearch(root.left);
if(root.val > val) return BSTsearch(root.right);
return root;
}
2.增加:增加的操作和查找类似 ,搜索二叉树知道叶子节点,添加到合适的叶子节点;
TreeNode BSTadd(TreeNode root, int val){
if(root == null) return new TreeNode(val);
if(root.val > val) root.left = BSTadd(root.left, val);
if(root.val < val) root.right = BSTadd(root.right, val);
return root;
}
3.删除:删除的情况比较复杂,可以分为三种情况
1.若该节点无左右节点则直接返回null;
2.若只有左节点或右节点则返回左节点或者右jiedian
3.即有左节点也有右节点,将该节点替换成左边最大值或者右边最小值,左边最大值为其左子树的最右边节点,右边最小值为右子树最左边的节点
TreeNode deleteNode(TreeNode root, int key){
if(root == null) return null;
if(root.val == key){
//1.第一种情况
if(root.left == null && root.right == null) return null;
//2.第二种情况
if(root.left == null) return root.right;
if(root.right == null) return root.left;
//3.第三种情况
TreeNode minNode = getMin(root.right);
root.val= minNode.val;
root.right = deleteNode(root.right, minNode.val);
} else if(root.val > key){
root.left = deleteNode(root.left, key);
} else if(root.val < key) {
root.right = deleteNode(root.right, key);
}
return root;
}
TreeNode getMin(TreeNode node){
while(node.left != null) node = node.left;
return node;
}