我們簡單討論了 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 實現
public Node search(Node root, int key)
{
// Base Cases: root is null or key is present at root
if (root==null || root.key==key)
return root;
// val is greater than root's key
if (root.key > key)
return search(root.left