我们简单讨论了 BST 的基本特性和操作。本章我们主要讨论 BST 中的两个基本操作 Search、Insertion。
1. Search a key
在 BST 中查找指定的 key,我们先把要查找的 key 和 root 节点比较,如果相等,则返回 root,否则如果 key 大于 root,那么我们递归的在右子树中查找,否则递归的在左子树中查找。
C 实现
struct node* search(struct node* root, int key)
{
// Base Cases: root is null or key is present at root
if (root == NULL || root->key == key)
return root;
// Key is greater than root's key
if (root->key < key)
return search(root->right, key);
// Key is smaller than root's key
return search(root->left, key);
}
Java 实现